3 * This source code is part of
7 * GROningen MAchine for Chemical Simulations
9 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11 * Copyright (c) 2001-2009, The GROMACS development team,
12 * check out http://www.gromacs.org for more information.
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
19 * If you want to redistribute modifications, please consider that
20 * scientific software is very special. Version control is crucial -
21 * bugs must be traceable. We will be happy to consider code for
22 * inclusion in the official distribution, but derived work must not
23 * be called official GROMACS. Details are found in the README & COPYING
24 * files - if they are missing, get the official version at www.gromacs.org.
26 * To help us fund GROMACS development, we humbly ask that you cite
27 * the papers on the package - you can find them in the top README file.
29 * For more info, check our website at http://www.gromacs.org
31 /*! \libinternal \file
33 * Defines gmx::OptionStorageTemplate template.
35 * \author Teemu Murtola <teemu.murtola@cbr.su.se>
37 * \ingroup module_options
39 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
40 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
45 #include <boost/scoped_ptr.hpp>
47 #include "../fatalerror/exceptions.h"
48 #include "../fatalerror/gmxassert.h"
50 #include "abstractoption.h"
51 #include "abstractoptionstorage.h"
58 /*! \libinternal \brief
59 * Templated base class for constructing option value storage classes.
61 * \tparam T Assignable type that stores a single option value.
63 * Provides an implementation of the clearSet(), valueCount(), and processSet()
64 * methods of AbstractOptionStorage, as well as a basic no-action
65 * implementation of processAll(). Two new virtual methods are added:
66 * processSetValues() and refreshValues(). The default implementation of
67 * processSetValues() does nothing, and refreshValues() is used to update
68 * secondary storage after values have been added/changed.
69 * This leaves typeString(), formatValue(), and convertValue() to be
70 * implemented in derived classes. processSetValues() and processAll() can
71 * also be implemented if necessary.
73 * Implements transaction support for adding values within a set: all calls to
74 * addValue() add the value to a temporary storage, processSetValues() operates
75 * on this temporary storage, and commitValues() then copies these values to
76 * the real storage. commitValues() provides a strong exception safety
77 * guarantee for the process (and it only throws if it runs out of memory).
80 * \ingroup module_options
83 class OptionStorageTemplate : public AbstractOptionStorage
86 //! Alias for the template class for use in base classes.
87 typedef OptionStorageTemplate<T> MyBase;
88 //! Type of the container that contains the current values.
89 typedef std::vector<T> ValueList;
91 virtual ~OptionStorageTemplate();
93 // No implementation in this class for the pure virtual methods, but
94 // the declarations are still included for clarity.
95 virtual const char *typeString() const = 0;
96 virtual int valueCount() const { return static_cast<int>(_values->size()); }
97 virtual std::string formatValue(int i) const = 0;
101 * Initializes the storage from option settings.
103 * \param[in] settings Option settings.
104 * \param[in] staticFlags Option flags that are always set and specify
105 * generic behavior of the option.
106 * \throws APIError if invalid settings have been provided.
109 OptionStorageTemplate(const OptionTemplate<T, U> &settings,
110 OptionFlags staticFlags = OptionFlags());
113 virtual void clearSet();
114 /*! \copydoc AbstractOptionStorage::convertValue()
116 * Derived classes should call addValue() after they have converted
117 * \p value to the storage type. It is allowed to call addValue()
118 * more than once, or not at all. OptionsAssigner::appendValue()
119 * provides the same exception safety guarantee as this method, so it
120 * should be considered whether the implementation can be made strongly
123 virtual void convertValue(const std::string &value) = 0;
125 * Processes values for a set after all have been converted.
127 * \param[in,out] values Valid values in the set.
128 * \throws InvalidInputError if the values do not form a valid set.
130 * This method is called after all convertValue() calls for a set.
131 * \p values contains all values that were validly converted by
132 * convertValue(). The derived class may alter the values, but should
133 * in such a case ensure that a correct number of values is produced.
134 * If the derived class throws, all values in \p values are discarded.
136 virtual void processSetValues(ValueList *values)
139 /*! \copydoc AbstractOptionStorage::processSet()
141 * OptionStorage template implements transaction support for a set of
142 * values in this method (see the class description), and provides a
143 * more detailed processSetValues() method that can be overridden in
144 * subclasses to process the actual values. Derived classes should
145 * override that method instead of this one if set value processing is
148 virtual void processSet();
149 /*! \copydoc AbstractOptionStorage::processAll()
151 * The implementation in OptionStorageTemplate does nothing.
153 virtual void processAll()
158 * Removes all values from the storage.
162 void clear() { _values->clear(); }
164 * Adds a value to a temporary storage.
166 * \param[in] value Value to add. A copy is made.
167 * \throws InvalidInputError if the maximum value count has been reached.
169 * Derived classes should call this function from the convertValue()
170 * implementation to add converted values to the storage.
171 * If the maximum value cont has been reached, the value is discarded
172 * and an exception is thrown.
174 * If adding values outside convertValue() (e.g., to set a custom
175 * default value), derived classes should call clearSet() before adding
176 * values (unless in the constructor) and commitValues() once all
179 void addValue(const T &value);
181 * Commits values added with addValue().
183 * If this function succeeds, values added with addValue() since the
184 * previous clearSet() are added to the storage for the option.
185 * Only throws in out-of-memory conditions, and provides the strong
186 * exception safety guarantee.
188 * See addValue() for cases where this method should be used in derived
191 * Calls refreshValues() and clearSet() if it is successful.
195 * Updates alternative store locations.
197 * Derived classes should override this method if they implement
198 * alternative store locations, and copy/translate values from the
199 * values() vector to these alternative storages. They should also
200 * call the base class implementation as part of their implementation.
202 * Should be called in derived classes if values are modified directly
203 * through the values() method, e.g., in processAll(). Does not need
204 * to be called if commitValues() is used.
206 * Does not throw, and derived classes should not change that.
208 virtual void refreshValues();
211 * Provides derived classes access to the current list of values.
213 * The non-const variant should only be used from processAll() in
214 * derived classes if necessary, and refreshValues() should be called
215 * if any changes are made.
217 ValueList &values() { return *_values; }
218 //! Provides derived classes access to the current list of values.
219 const ValueList &values() const { return *_values; }
223 * Vector for temporary storage of values before commitSet() is called.
225 ValueList _setValues;
227 * Vector for primary storage of option values.
229 * Is never NULL; points either to externally provided vector, or an
230 * internally allocated one. The allocation is performed by the
233 * Primarily, modifications to values are done only to this storage,
234 * and other storage locations are updated only when refreshValues() is
240 boost::scoped_ptr<ValueList> _ownedValues;
241 boost::scoped_ptr<T> _defaultValueIfSet;
243 // Copy and assign disallowed by base.
247 template <typename T>
249 OptionStorageTemplate<T>::OptionStorageTemplate(const OptionTemplate<T, U> &settings,
250 OptionFlags staticFlags)
251 : AbstractOptionStorage(settings, staticFlags),
252 _values(settings._storeVector),
253 _store(settings._store),
254 _countptr(settings._countptr)
258 // The flag should be set for proper error checking.
259 GMX_RELEASE_ASSERT(!hasFlag(efExternalValueVector),
260 "Internal inconsistency");
261 _ownedValues.reset(new std::vector<T>);
262 _values = _ownedValues.get();
264 if (hasFlag(efNoDefaultValue)
265 && (settings._defaultValue != NULL
266 || settings._defaultValueIfSet != NULL))
268 GMX_THROW(APIError("Option does not support default value, but one is set"));
270 if (_store != NULL && _countptr == NULL && !hasFlag(efVector)
271 && minValueCount() != maxValueCount())
273 GMX_THROW(APIError("Count storage is not set, although the number of produced values is not known"));
275 if (!hasFlag(efNoDefaultValue))
277 setFlag(efHasDefaultValue);
278 if (settings._defaultValue != NULL)
281 addValue(*settings._defaultValue);
282 // TODO: This is a bit hairy, as it indirectly calls a virtual function.
285 else if (_ownedValues.get() == NULL && _store != NULL)
288 int count = (settings.isVector() ?
289 settings._maxValueCount : settings._minValueCount);
290 for (int i = 0; i < count; ++i)
292 _values->push_back(_store[i]);
295 if (settings._defaultValueIfSet != NULL)
297 if (hasFlag(efMulti))
299 GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
301 _defaultValueIfSet.reset(new T(*settings._defaultValueIfSet));
304 setFlag(efClearOnNextSet);
308 template <typename T>
309 OptionStorageTemplate<T>::~OptionStorageTemplate()
314 template <typename T>
315 void OptionStorageTemplate<T>::clearSet()
321 template <typename T>
322 void OptionStorageTemplate<T>::processSet()
324 processSetValues(&_setValues);
325 if (_setValues.empty() && _defaultValueIfSet.get() != NULL)
327 addValue(*_defaultValueIfSet);
328 setFlag(efHasDefaultValue);
332 clearFlag(efHasDefaultValue);
334 if (!hasFlag(efDontCheckMinimumCount)
335 && _setValues.size() < static_cast<size_t>(minValueCount()))
338 GMX_THROW(InvalidInputError("Too few (valid) values"));
344 template <typename T>
345 void OptionStorageTemplate<T>::addValue(const T &value)
347 if (maxValueCount() >= 0
348 && _setValues.size() >= static_cast<size_t>(maxValueCount()))
350 GMX_THROW(InvalidInputError("Too many values"));
352 _setValues.push_back(value);
356 template <typename T>
357 void OptionStorageTemplate<T>::commitValues()
359 if (hasFlag(efClearOnNextSet))
361 _values->swap(_setValues);
362 clearFlag(efClearOnNextSet);
366 _values->insert(_values->end(), _setValues.begin(), _setValues.end());
373 template <typename T>
374 void OptionStorageTemplate<T>::refreshValues()
376 if (_countptr != NULL)
378 *_countptr = static_cast<int>(_values->size());
382 for (size_t i = 0; i < _values->size(); ++i)
384 _store[i] = (*_values)[i];