Merge branch release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / options / optionstoragetemplate.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \libinternal \file
36  * \brief
37  * Defines gmx::OptionStorageTemplate template.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inlibraryapi
41  * \ingroup module_options
42  */
43 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
44 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
45
46 #include <string>
47 #include <vector>
48
49 #include <boost/scoped_ptr.hpp>
50
51 #include "../utility/exceptions.h"
52 #include "../utility/gmxassert.h"
53
54 #include "abstractoption.h"
55 #include "abstractoptionstorage.h"
56
57 namespace gmx
58 {
59
60 class Options;
61
62 /*! \libinternal \brief
63  * Templated base class for constructing option value storage classes.
64  *
65  * \tparam T Assignable type that stores a single option value.
66  *
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.
76  *
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).
82  *
83  * \inlibraryapi
84  * \ingroup module_options
85  */
86 template <typename T>
87 class OptionStorageTemplate : public AbstractOptionStorage
88 {
89     public:
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;
94
95         virtual ~OptionStorageTemplate();
96
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()
102          *
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.
107          */
108         virtual std::string formatValue(int i) const;
109
110     protected:
111         /*! \brief
112          * Initializes the storage from option settings.
113          *
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.
118          */
119         template <class U>
120         explicit OptionStorageTemplate(const OptionTemplate<T, U> &settings,
121                                        OptionFlags staticFlags = OptionFlags());
122
123
124         virtual void clearSet();
125         /*! \copydoc gmx::AbstractOptionStorage::convertValue()
126          *
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
132          * exception safe.
133          */
134         virtual void convertValue(const std::string &value) = 0;
135         /*! \brief
136          * Processes values for a set after all have been converted.
137          *
138          * \param[in,out] values Valid values in the set.
139          * \throws InvalidInputError if the values do not form a valid set.
140          *
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.
146          */
147         virtual void processSetValues(ValueList *values)
148         {
149         }
150         /*! \copydoc gmx::AbstractOptionStorage::processSet()
151          *
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
157          * necessary.
158          */
159         virtual void processSet();
160         /*! \copydoc gmx::AbstractOptionStorage::processAll()
161          *
162          * The implementation in OptionStorageTemplate does nothing.
163          */
164         virtual void processAll()
165         {
166         }
167         /*! \brief
168          * Formats a single value as a string.
169          *
170          * \param[in] value  Value to format.
171          * \returns   \p value formatted as a string.
172          *
173          * The derived class must provide this method to format values a
174          * strings.  Called by formatValue() to do the actual formatting.
175          */
176         virtual std::string formatSingleValue(const T &value) const = 0;
177
178         /*! \brief
179          * Removes all values from the storage.
180          *
181          * Does not throw.
182          */
183         void clear() { values_->clear(); }
184         /*! \brief
185          * Adds a value to a temporary storage.
186          *
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.
190          *
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.
195          *
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
199          * values are added.
200          */
201         void addValue(const T &value);
202         /*! \brief
203          * Commits values added with addValue().
204          *
205          * \throws std::bad_alloc if out of memory.
206          *
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.
211          *
212          * See addValue() for cases where this method should be used in derived
213          * classes.
214          *
215          * Calls refreshValues() and clearSet() if it is successful.
216          */
217         void commitValues();
218         /*! \brief
219          * Updates alternative store locations.
220          *
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.
225          *
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.
229          *
230          * Does not throw, and derived classes should not change that.
231          */
232         virtual void refreshValues();
233
234         /*! \brief
235          * Sets the default value for the option.
236          *
237          * \param[in] value  Default value to set.
238          * \throws    std::bad_alloc if out of memory.
239          *
240          * This method can be used from the derived class constructor to
241          * programmatically set a default value.
242          */
243         void setDefaultValue(const T &value);
244         /*! \brief
245          * Sets the default value if set for the option.
246          *
247          * \param[in] value  Default value to set.
248          * \throws    std::bad_alloc if out of memory.
249          *
250          * This method can be used from the derived class constructor to
251          * programmatically set a default value.
252          */
253         void setDefaultValueIfSet(const T &value);
254
255         /*! \brief
256          * Provides derived classes access to the current list of values.
257          *
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.
261          */
262         ValueList       &values() { return *values_; }
263         //! Provides derived classes access to the current list of values.
264         const ValueList &values() const { return *values_; }
265
266     private:
267         /*! \brief
268          * Vector for temporary storage of values before commitSet() is called.
269          */
270         ValueList               setValues_;
271         /*! \brief
272          * Vector for primary storage of option values.
273          *
274          * Is never NULL; points either to externally provided vector, or an
275          * internally allocated one.  The allocation is performed by the
276          * constructor.
277          *
278          * Primarily, modifications to values are done only to this storage,
279          * and other storage locations are updated only when refreshValues() is
280          * called.
281          */
282         ValueList                   *values_;
283         T                           *store_;
284         int                         *countptr_;
285         boost::scoped_ptr<ValueList> ownedValues_;
286         boost::scoped_ptr<T>         defaultValueIfSet_;
287
288         // Copy and assign disallowed by base.
289 };
290
291
292 template <typename T>
293 template <class U>
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_)
300 {
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)))
304     {
305         GMX_THROW(APIError("Cannot set user-allocated storage for arbitrary number of values"));
306     }
307     if (values_ == NULL)
308     {
309         ownedValues_.reset(new std::vector<T>);
310         values_ = ownedValues_.get();
311     }
312     if (hasFlag(efOption_NoDefaultValue)
313         && (settings.defaultValue_ != NULL
314             || settings.defaultValueIfSet_ != NULL))
315     {
316         GMX_THROW(APIError("Option does not support default value, but one is set"));
317     }
318     if (store_ != NULL && countptr_ == NULL && !isVector()
319         && minValueCount() != maxValueCount())
320     {
321         GMX_THROW(APIError("Count storage is not set, although the number of produced values is not known"));
322     }
323     if (!hasFlag(efOption_NoDefaultValue))
324     {
325         setFlag(efOption_HasDefaultValue);
326         if (settings.defaultValue_ != NULL)
327         {
328             setDefaultValue(*settings.defaultValue_);
329         }
330         else if (ownedValues_.get() != NULL && store_ != NULL)
331         {
332             values_->clear();
333             int count = (settings.isVector() ?
334                          settings.maxValueCount_ : settings.minValueCount_);
335             for (int i = 0; i < count; ++i)
336             {
337                 values_->push_back(store_[i]);
338             }
339         }
340         if (settings.defaultValueIfSet_ != NULL)
341         {
342             setDefaultValueIfSet(*settings.defaultValueIfSet_);
343         }
344     }
345 }
346
347
348 template <typename T>
349 OptionStorageTemplate<T>::~OptionStorageTemplate()
350 {
351 }
352
353
354 template <typename T>
355 std::string OptionStorageTemplate<T>::formatValue(int i) const
356 {
357     GMX_RELEASE_ASSERT(i == DefaultValueIfSetIndex || (i >= 0 && i < valueCount()),
358                        "Invalid value index");
359     if (i == DefaultValueIfSetIndex)
360     {
361         if (defaultValueIfSet_.get() != NULL)
362         {
363             return formatSingleValue(*defaultValueIfSet_);
364         }
365         return std::string();
366     }
367     return formatSingleValue(values()[i]);
368 }
369
370
371 template <typename T>
372 void OptionStorageTemplate<T>::clearSet()
373 {
374     setValues_.clear();
375 }
376
377
378 template <typename T>
379 void OptionStorageTemplate<T>::processSet()
380 {
381     processSetValues(&setValues_);
382     if (setValues_.empty() && defaultValueIfSet_.get() != NULL)
383     {
384         addValue(*defaultValueIfSet_);
385         setFlag(efOption_HasDefaultValue);
386     }
387     else
388     {
389         clearFlag(efOption_HasDefaultValue);
390     }
391     if (!hasFlag(efOption_DontCheckMinimumCount)
392         && setValues_.size() < static_cast<size_t>(minValueCount()))
393     {
394         GMX_THROW(InvalidInputError("Too few (valid) values"));
395     }
396     commitValues();
397 }
398
399
400 template <typename T>
401 void OptionStorageTemplate<T>::addValue(const T &value)
402 {
403     if (maxValueCount() >= 0
404         && setValues_.size() >= static_cast<size_t>(maxValueCount()))
405     {
406         GMX_THROW(InvalidInputError("Too many values"));
407     }
408     setValues_.push_back(value);
409 }
410
411
412 template <typename T>
413 void OptionStorageTemplate<T>::commitValues()
414 {
415     if (hasFlag(efOption_ClearOnNextSet))
416     {
417         values_->swap(setValues_);
418     }
419     else
420     {
421         values_->insert(values_->end(), setValues_.begin(), setValues_.end());
422     }
423     clearSet();
424     refreshValues();
425 }
426
427
428 template <typename T>
429 void OptionStorageTemplate<T>::refreshValues()
430 {
431     if (countptr_ != NULL)
432     {
433         *countptr_ = static_cast<int>(values_->size());
434     }
435     if (store_ != NULL)
436     {
437         for (size_t i = 0; i < values_->size(); ++i)
438         {
439             store_[i] = (*values_)[i];
440         }
441     }
442 }
443
444
445 template <typename T>
446 void OptionStorageTemplate<T>::setDefaultValue(const T &value)
447 {
448     if (hasFlag(efOption_NoDefaultValue))
449     {
450         GMX_THROW(APIError("Option does not support default value, but one is set"));
451     }
452     if (hasFlag(efOption_HasDefaultValue))
453     {
454         setFlag(efOption_ExplicitDefaultValue);
455         clear();
456         clearSet();
457         addValue(value);
458         // TODO: As this is called from the constructor, it should not call
459         // virtual functions.
460         commitValues();
461     }
462 }
463
464
465 template <typename T>
466 void OptionStorageTemplate<T>::setDefaultValueIfSet(const T &value)
467 {
468     if (hasFlag(efOption_NoDefaultValue))
469     {
470         GMX_THROW(APIError("Option does not support default value, but one is set"));
471     }
472     if (hasFlag(efOption_MultipleTimes))
473     {
474         GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
475     }
476     defaultValueIfSet_.reset(new T(value));
477 }
478
479 } // namespace gmx
480
481 #endif