2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2012, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
35 /*! \libinternal \file
37 * Defines gmx::OptionStorageTemplate template.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_options
43 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
44 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
49 #include <boost/scoped_ptr.hpp>
51 #include "../utility/exceptions.h"
52 #include "../utility/gmxassert.h"
54 #include "abstractoption.h"
55 #include "abstractoptionstorage.h"
62 /*! \libinternal \brief
63 * Templated base class for constructing option value storage classes.
65 * \tparam T Assignable type that stores a single option value.
67 * Provides an implementation of the clearSet(), valueCount(), and processSet()
68 * methods of AbstractOptionStorage, as well as a basic no-action
69 * implementation of processAll(). Two new virtual methods are added:
70 * processSetValues() and refreshValues(). The default implementation of
71 * processSetValues() does nothing, and refreshValues() is used to update
72 * secondary storage after values have been added/changed.
73 * This leaves typeString(), formatValue(), and convertValue() to be
74 * implemented in derived classes. processSetValues() and processAll() can
75 * also be implemented if necessary.
77 * Implements transaction support for adding values within a set: all calls to
78 * addValue() add the value to a temporary storage, processSetValues() operates
79 * on this temporary storage, and commitValues() then copies these values to
80 * the real storage. commitValues() provides a strong exception safety
81 * guarantee for the process (and it only throws if it runs out of memory).
84 * \ingroup module_options
87 class OptionStorageTemplate : public AbstractOptionStorage
90 //! Alias for the template class for use in base classes.
91 typedef OptionStorageTemplate<T> MyBase;
92 //! Type of the container that contains the current values.
93 typedef std::vector<T> ValueList;
95 virtual ~OptionStorageTemplate();
97 // No implementation in this class for the pure virtual methods, but
98 // the declarations are still included for clarity.
99 virtual const char *typeString() const = 0;
100 virtual int valueCount() const { return static_cast<int>(values_->size()); }
101 /*! \copydoc gmx::AbstractOptionStorage::formatValue()
103 * OptionStorageTemplate implements handling of DefaultValueIfSetIndex
104 * in this method, as well as checking that \p i is a valid index.
105 * Derived classes must implement formatSingleValue() to provide the
106 * actual formatting for a value of type \p T.
108 virtual std::string formatValue(int i) const;
112 * Initializes the storage from option settings.
114 * \param[in] settings Option settings.
115 * \param[in] staticFlags Option flags that are always set and specify
116 * generic behavior of the option.
117 * \throws APIError if invalid settings have been provided.
120 explicit OptionStorageTemplate(const OptionTemplate<T, U> &settings,
121 OptionFlags staticFlags = OptionFlags());
124 virtual void clearSet();
125 /*! \copydoc gmx::AbstractOptionStorage::convertValue()
127 * Derived classes should call addValue() after they have converted
128 * \p value to the storage type. It is allowed to call addValue()
129 * more than once, or not at all. OptionsAssigner::appendValue()
130 * provides the same exception safety guarantee as this method, so it
131 * should be considered whether the implementation can be made strongly
134 virtual void convertValue(const std::string &value) = 0;
136 * Processes values for a set after all have been converted.
138 * \param[in,out] values Valid values in the set.
139 * \throws InvalidInputError if the values do not form a valid set.
141 * This method is called after all convertValue() calls for a set.
142 * \p values contains all values that were validly converted by
143 * convertValue(). The derived class may alter the values, but should
144 * in such a case ensure that a correct number of values is produced.
145 * If the derived class throws, all values in \p values are discarded.
147 virtual void processSetValues(ValueList *values)
150 /*! \copydoc gmx::AbstractOptionStorage::processSet()
152 * OptionStorageTemplate implements transaction support for a set of
153 * values in this method (see the class description), and provides a
154 * more detailed processSetValues() method that can be overridden in
155 * subclasses to process the actual values. Derived classes should
156 * override that method instead of this one if set value processing is
159 virtual void processSet();
160 /*! \copydoc gmx::AbstractOptionStorage::processAll()
162 * The implementation in OptionStorageTemplate does nothing.
164 virtual void processAll()
168 * Formats a single value as a string.
170 * \param[in] value Value to format.
171 * \returns \p value formatted as a string.
173 * The derived class must provide this method to format values a
174 * strings. Called by formatValue() to do the actual formatting.
176 virtual std::string formatSingleValue(const T &value) const = 0;
179 * Removes all values from the storage.
183 void clear() { values_->clear(); }
185 * Adds a value to a temporary storage.
187 * \param[in] value Value to add. A copy is made.
188 * \throws std::bad_alloc if out of memory.
189 * \throws InvalidInputError if the maximum value count has been reached.
191 * Derived classes should call this function from the convertValue()
192 * implementation to add converted values to the storage.
193 * If the maximum value count has been reached, the value is discarded
194 * and an exception is thrown.
196 * If adding values outside convertValue() (e.g., to set a custom
197 * default value), derived classes should call clearSet() before adding
198 * values (unless in the constructor) and commitValues() once all
201 void addValue(const T &value);
203 * Commits values added with addValue().
205 * \throws std::bad_alloc if out of memory.
207 * If this function succeeds, values added with addValue() since the
208 * previous clearSet() are added to the storage for the option.
209 * Only throws in out-of-memory conditions, and provides the strong
210 * exception safety guarantee.
212 * See addValue() for cases where this method should be used in derived
215 * Calls refreshValues() and clearSet() if it is successful.
219 * Updates alternative store locations.
221 * Derived classes should override this method if they implement
222 * alternative store locations, and copy/translate values from the
223 * values() vector to these alternative storages. They should also
224 * call the base class implementation as part of their implementation.
226 * Should be called in derived classes if values are modified directly
227 * through the values() method, e.g., in processAll(). Does not need
228 * to be called if commitValues() is used.
230 * Does not throw, and derived classes should not change that.
232 virtual void refreshValues();
235 * Sets the default value for the option.
237 * \param[in] value Default value to set.
238 * \throws std::bad_alloc if out of memory.
240 * This method can be used from the derived class constructor to
241 * programmatically set a default value.
243 void setDefaultValue(const T &value);
245 * Sets the default value if set for the option.
247 * \param[in] value Default value to set.
248 * \throws std::bad_alloc if out of memory.
250 * This method can be used from the derived class constructor to
251 * programmatically set a default value.
253 void setDefaultValueIfSet(const T &value);
256 * Provides derived classes access to the current list of values.
258 * The non-const variant should only be used from processAll() in
259 * derived classes if necessary, and refreshValues() should be called
260 * if any changes are made.
262 ValueList &values() { return *values_; }
263 //! Provides derived classes access to the current list of values.
264 const ValueList &values() const { return *values_; }
268 * Vector for temporary storage of values before commitSet() is called.
270 ValueList setValues_;
272 * Vector for primary storage of option values.
274 * Is never NULL; points either to externally provided vector, or an
275 * internally allocated one. The allocation is performed by the
278 * Primarily, modifications to values are done only to this storage,
279 * and other storage locations are updated only when refreshValues() is
285 boost::scoped_ptr<ValueList> ownedValues_;
286 boost::scoped_ptr<T> defaultValueIfSet_;
288 // Copy and assign disallowed by base.
292 template <typename T>
294 OptionStorageTemplate<T>::OptionStorageTemplate(const OptionTemplate<T, U> &settings,
295 OptionFlags staticFlags)
296 : AbstractOptionStorage(settings, staticFlags),
297 values_(settings.storeVector_),
298 store_(settings.store_),
299 countptr_(settings.countptr_)
301 // If the maximum number of values is not known, storage to
302 // caller-allocated memory is unsafe.
303 if (store_ != NULL && (maxValueCount() < 0 || hasFlag(efOption_MultipleTimes)))
305 GMX_THROW(APIError("Cannot set user-allocated storage for arbitrary number of values"));
309 ownedValues_.reset(new std::vector<T>);
310 values_ = ownedValues_.get();
312 if (hasFlag(efOption_NoDefaultValue)
313 && (settings.defaultValue_ != NULL
314 || settings.defaultValueIfSet_ != NULL))
316 GMX_THROW(APIError("Option does not support default value, but one is set"));
318 if (store_ != NULL && countptr_ == NULL && !isVector()
319 && minValueCount() != maxValueCount())
321 GMX_THROW(APIError("Count storage is not set, although the number of produced values is not known"));
323 if (!hasFlag(efOption_NoDefaultValue))
325 setFlag(efOption_HasDefaultValue);
326 if (settings.defaultValue_ != NULL)
328 setDefaultValue(*settings.defaultValue_);
330 else if (ownedValues_.get() != NULL && store_ != NULL)
333 int count = (settings.isVector() ?
334 settings.maxValueCount_ : settings.minValueCount_);
335 for (int i = 0; i < count; ++i)
337 values_->push_back(store_[i]);
340 if (settings.defaultValueIfSet_ != NULL)
342 setDefaultValueIfSet(*settings.defaultValueIfSet_);
348 template <typename T>
349 OptionStorageTemplate<T>::~OptionStorageTemplate()
354 template <typename T>
355 std::string OptionStorageTemplate<T>::formatValue(int i) const
357 GMX_RELEASE_ASSERT(i == DefaultValueIfSetIndex || (i >= 0 && i < valueCount()),
358 "Invalid value index");
359 if (i == DefaultValueIfSetIndex)
361 if (defaultValueIfSet_.get() != NULL)
363 return formatSingleValue(*defaultValueIfSet_);
365 return std::string();
367 return formatSingleValue(values()[i]);
371 template <typename T>
372 void OptionStorageTemplate<T>::clearSet()
378 template <typename T>
379 void OptionStorageTemplate<T>::processSet()
381 processSetValues(&setValues_);
382 if (setValues_.empty() && defaultValueIfSet_.get() != NULL)
384 addValue(*defaultValueIfSet_);
385 setFlag(efOption_HasDefaultValue);
389 clearFlag(efOption_HasDefaultValue);
391 if (!hasFlag(efOption_DontCheckMinimumCount)
392 && setValues_.size() < static_cast<size_t>(minValueCount()))
394 GMX_THROW(InvalidInputError("Too few (valid) values"));
400 template <typename T>
401 void OptionStorageTemplate<T>::addValue(const T &value)
403 if (maxValueCount() >= 0
404 && setValues_.size() >= static_cast<size_t>(maxValueCount()))
406 GMX_THROW(InvalidInputError("Too many values"));
408 setValues_.push_back(value);
412 template <typename T>
413 void OptionStorageTemplate<T>::commitValues()
415 if (hasFlag(efOption_ClearOnNextSet))
417 values_->swap(setValues_);
421 values_->insert(values_->end(), setValues_.begin(), setValues_.end());
428 template <typename T>
429 void OptionStorageTemplate<T>::refreshValues()
431 if (countptr_ != NULL)
433 *countptr_ = static_cast<int>(values_->size());
437 for (size_t i = 0; i < values_->size(); ++i)
439 store_[i] = (*values_)[i];
445 template <typename T>
446 void OptionStorageTemplate<T>::setDefaultValue(const T &value)
448 if (hasFlag(efOption_NoDefaultValue))
450 GMX_THROW(APIError("Option does not support default value, but one is set"));
452 if (hasFlag(efOption_HasDefaultValue))
454 setFlag(efOption_ExplicitDefaultValue);
458 // TODO: As this is called from the constructor, it should not call
459 // virtual functions.
465 template <typename T>
466 void OptionStorageTemplate<T>::setDefaultValueIfSet(const T &value)
468 if (hasFlag(efOption_NoDefaultValue))
470 GMX_THROW(APIError("Option does not support default value, but one is set"));
472 if (hasFlag(efOption_MultipleTimes))
474 GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
476 defaultValueIfSet_.reset(new T(value));