Merge release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / options / optionstoragetemplate.h
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
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.
13
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.
18  *
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.
25  *
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.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \libinternal \file
32  * \brief
33  * Defines gmx::OptionStorageTemplate template.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \inlibraryapi
37  * \ingroup module_options
38  */
39 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
40 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
41
42 #include <string>
43 #include <vector>
44
45 #include <boost/scoped_ptr.hpp>
46
47 #include "../utility/exceptions.h"
48 #include "../utility/gmxassert.h"
49
50 #include "abstractoption.h"
51 #include "abstractoptionstorage.h"
52
53 namespace gmx
54 {
55
56 class Options;
57
58 /*! \libinternal \brief
59  * Templated base class for constructing option value storage classes.
60  *
61  * \tparam T Assignable type that stores a single option value.
62  *
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.
72  *
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).
78  *
79  * \inlibraryapi
80  * \ingroup module_options
81  */
82 template <typename T>
83 class OptionStorageTemplate : public AbstractOptionStorage
84 {
85     public:
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;
90
91         virtual ~OptionStorageTemplate();
92
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         /*! \copydoc AbstractOptionStorage::formatValue()
98          *
99          * OptionStorageTemplate implements handling of DefaultValueIfSetIndex
100          * in this method, as well as checking that \p i is a valid index.
101          * Derived classes must implement formatSingleValue() to provide the
102          * actual formatting for a value of type \p T.
103          */
104         virtual std::string formatValue(int i) const;
105
106     protected:
107         /*! \brief
108          * Initializes the storage from option settings.
109          *
110          * \param[in] settings  Option settings.
111          * \param[in] staticFlags Option flags that are always set and specify
112          *      generic behavior of the option.
113          * \throws  APIError if invalid settings have been provided.
114          */
115         template <class U>
116         OptionStorageTemplate(const OptionTemplate<T, U> &settings,
117                               OptionFlags staticFlags = OptionFlags());
118
119
120         virtual void clearSet();
121         /*! \copydoc AbstractOptionStorage::convertValue()
122          *
123          * Derived classes should call addValue() after they have converted
124          * \p value to the storage type.  It is allowed to call addValue()
125          * more than once, or not at all.  OptionsAssigner::appendValue()
126          * provides the same exception safety guarantee as this method, so it
127          * should be considered whether the implementation can be made strongly
128          * exception safe.
129          */
130         virtual void convertValue(const std::string &value) = 0;
131         /*! \brief
132          * Processes values for a set after all have been converted.
133          *
134          * \param[in,out] values Valid values in the set.
135          * \throws InvalidInputError if the values do not form a valid set.
136          *
137          * This method is called after all convertValue() calls for a set.
138          * \p values contains all values that were validly converted by
139          * convertValue().  The derived class may alter the values, but should
140          * in such a case ensure that a correct number of values is produced.
141          * If the derived class throws, all values in \p values are discarded.
142          */
143         virtual void processSetValues(ValueList *values)
144         {
145         }
146         /*! \copydoc AbstractOptionStorage::processSet()
147          *
148          * OptionStorageTemplate implements transaction support for a set of
149          * values in this method (see the class description), and provides a
150          * more detailed processSetValues() method that can be overridden in
151          * subclasses to process the actual values.  Derived classes should
152          * override that method instead of this one if set value processing is
153          * necessary.
154          */
155         virtual void processSet();
156         /*! \copydoc AbstractOptionStorage::processAll()
157          *
158          * The implementation in OptionStorageTemplate does nothing.
159          */
160         virtual void processAll()
161         {
162         }
163         /*! \brief
164          * Formats a single value as a string.
165          *
166          * \param[in] value  Value to format.
167          * \returns   \p value formatted as a string.
168          *
169          * The derived class must provide this method to format values a
170          * strings.  Called by formatValue() to do the actual formatting.
171          */
172         virtual std::string formatSingleValue(const T &value) const = 0;
173
174         /*! \brief
175          * Removes all values from the storage.
176          *
177          * Does not throw.
178          */
179         void clear() { _values->clear(); }
180         /*! \brief
181          * Adds a value to a temporary storage.
182          *
183          * \param[in] value  Value to add. A copy is made.
184          * \throws std::bad_alloc if out of memory.
185          * \throws InvalidInputError if the maximum value count has been reached.
186          *
187          * Derived classes should call this function from the convertValue()
188          * implementation to add converted values to the storage.
189          * If the maximum value count has been reached, the value is discarded
190          * and an exception is thrown.
191          *
192          * If adding values outside convertValue() (e.g., to set a custom
193          * default value), derived classes should call clearSet() before adding
194          * values (unless in the constructor) and commitValues() once all
195          * values are added.
196          */
197         void addValue(const T &value);
198         /*! \brief
199          * Commits values added with addValue().
200          *
201          * \throws std::bad_alloc if out of memory.
202          *
203          * If this function succeeds, values added with addValue() since the
204          * previous clearSet() are added to the storage for the option.
205          * Only throws in out-of-memory conditions, and provides the strong
206          * exception safety guarantee.
207          *
208          * See addValue() for cases where this method should be used in derived
209          * classes.
210          *
211          * Calls refreshValues() and clearSet() if it is successful.
212          */
213         void commitValues();
214         /*! \brief
215          * Updates alternative store locations.
216          *
217          * Derived classes should override this method if they implement
218          * alternative store locations, and copy/translate values from the
219          * values() vector to these alternative storages.  They should also
220          * call the base class implementation as part of their implementation.
221          *
222          * Should be called in derived classes if values are modified directly
223          * through the values() method, e.g., in processAll().  Does not need
224          * to be called if commitValues() is used.
225          *
226          * Does not throw, and derived classes should not change that.
227          */
228         virtual void refreshValues();
229
230         /*! \brief
231          * Provides derived classes access to the current list of values.
232          *
233          * The non-const variant should only be used from processAll() in
234          * derived classes if necessary, and refreshValues() should be called
235          * if any changes are made.
236          */
237         ValueList &values() { return *_values; }
238         //! Provides derived classes access to the current list of values.
239         const ValueList &values() const { return *_values; }
240
241     private:
242         /*! \brief
243          * Vector for temporary storage of values before commitSet() is called.
244          */
245         ValueList               _setValues;
246         /*! \brief
247          * Vector for primary storage of option values.
248          *
249          * Is never NULL; points either to externally provided vector, or an
250          * internally allocated one.  The allocation is performed by the
251          * constructor.
252          *
253          * Primarily, modifications to values are done only to this storage,
254          * and other storage locations are updated only when refreshValues() is
255          * called.
256          */
257         ValueList              *_values;
258         T                      *_store;
259         int                    *_countptr;
260         boost::scoped_ptr<ValueList> _ownedValues;
261         boost::scoped_ptr<T>    _defaultValueIfSet;
262
263         // Copy and assign disallowed by base.
264 };
265
266
267 template <typename T>
268 template <class U>
269 OptionStorageTemplate<T>::OptionStorageTemplate(const OptionTemplate<T, U> &settings,
270                                                 OptionFlags staticFlags)
271     : AbstractOptionStorage(settings, staticFlags),
272       _values(settings._storeVector),
273       _store(settings._store),
274       _countptr(settings._countptr)
275 {
276     if (_values == NULL)
277     {
278         // The flag should be set for proper error checking.
279         GMX_RELEASE_ASSERT(!hasFlag(efExternalValueVector),
280                            "Internal inconsistency");
281         _ownedValues.reset(new std::vector<T>);
282         _values = _ownedValues.get();
283     }
284     if (hasFlag(efNoDefaultValue)
285         && (settings._defaultValue != NULL
286             || settings._defaultValueIfSet != NULL))
287     {
288         GMX_THROW(APIError("Option does not support default value, but one is set"));
289     }
290     if (_store != NULL && _countptr == NULL && !hasFlag(efVector)
291         && minValueCount() != maxValueCount())
292     {
293         GMX_THROW(APIError("Count storage is not set, although the number of produced values is not known"));
294     }
295     if (!hasFlag(efNoDefaultValue))
296     {
297         setFlag(efHasDefaultValue);
298         if (settings._defaultValue != NULL)
299         {
300             _values->clear();
301             addValue(*settings._defaultValue);
302             // TODO: This is a bit hairy, as it indirectly calls a virtual function.
303             commitValues();
304         }
305         else if (_ownedValues.get() != NULL && _store != NULL)
306         {
307             _values->clear();
308             int count = (settings.isVector() ?
309                             settings._maxValueCount : settings._minValueCount);
310             for (int i = 0; i < count; ++i)
311             {
312                 _values->push_back(_store[i]);
313             }
314         }
315         if (settings._defaultValueIfSet != NULL)
316         {
317             if (hasFlag(efMulti))
318             {
319                 GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
320             }
321             _defaultValueIfSet.reset(new T(*settings._defaultValueIfSet));
322         }
323     }
324     setFlag(efClearOnNextSet);
325 }
326
327
328 template <typename T>
329 OptionStorageTemplate<T>::~OptionStorageTemplate()
330 {
331 }
332
333
334 template <typename T>
335 std::string OptionStorageTemplate<T>::formatValue(int i) const
336 {
337     GMX_RELEASE_ASSERT(i == DefaultValueIfSetIndex || (i >= 0 && i < valueCount()),
338                        "Invalid value index");
339     if (i == DefaultValueIfSetIndex)
340     {
341         if (_defaultValueIfSet.get() != NULL)
342         {
343             return formatSingleValue(*_defaultValueIfSet);
344         }
345         return std::string();
346     }
347     return formatSingleValue(values()[i]);
348 }
349
350
351 template <typename T>
352 void OptionStorageTemplate<T>::clearSet()
353 {
354     _setValues.clear();
355 }
356
357
358 template <typename T>
359 void OptionStorageTemplate<T>::processSet()
360 {
361     processSetValues(&_setValues);
362     if (_setValues.empty() && _defaultValueIfSet.get() != NULL)
363     {
364         addValue(*_defaultValueIfSet);
365         setFlag(efHasDefaultValue);
366     }
367     else
368     {
369         clearFlag(efHasDefaultValue);
370     }
371     if (!hasFlag(efDontCheckMinimumCount)
372         && _setValues.size() < static_cast<size_t>(minValueCount()))
373     {
374         clearSet();
375         GMX_THROW(InvalidInputError("Too few (valid) values"));
376     }
377     commitValues();
378 }
379
380
381 template <typename T>
382 void OptionStorageTemplate<T>::addValue(const T &value)
383 {
384     if (maxValueCount() >= 0
385         && _setValues.size() >= static_cast<size_t>(maxValueCount()))
386     {
387         GMX_THROW(InvalidInputError("Too many values"));
388     }
389     _setValues.push_back(value);
390 }
391
392
393 template <typename T>
394 void OptionStorageTemplate<T>::commitValues()
395 {
396     if (hasFlag(efClearOnNextSet))
397     {
398         _values->swap(_setValues);
399         clearFlag(efClearOnNextSet);
400     }
401     else
402     {
403         _values->insert(_values->end(), _setValues.begin(), _setValues.end());
404     }
405     clearSet();
406     refreshValues();
407 }
408
409
410 template <typename T>
411 void OptionStorageTemplate<T>::refreshValues()
412 {
413     if (_countptr != NULL)
414     {
415         *_countptr = static_cast<int>(_values->size());
416     }
417     if (_store != NULL)
418     {
419         for (size_t i = 0; i < _values->size(); ++i)
420         {
421             _store[i] = (*_values)[i];
422         }
423     }
424 }
425
426 } // namespace gmx
427
428 #endif