2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010-2018, The GROMACS development team.
5 * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
36 /*! \libinternal \file
38 * Defines gmx::OptionStorageTemplate template.
40 * \author Teemu Murtola <teemu.murtola@gmail.com>
42 * \ingroup module_options
44 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
45 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
51 #include "gromacs/options/abstractoption.h"
52 #include "gromacs/options/abstractoptionstorage.h"
53 #include "gromacs/utility/any.h"
54 #include "gromacs/utility/arrayref.h"
55 #include "gromacs/utility/basedefinitions.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/gmxassert.h"
59 #include "valueconverter.h"
60 #include "valuestore.h"
67 /*! \libinternal \brief
68 * Templated base class for constructing option value storage classes.
70 * \tparam T Assignable type that stores a single option value.
72 * Provides an implementation of the clearSet(), valueCount(), processSet(),
73 * and defaultValuesAsStrings() methods of AbstractOptionStorage, as well as a
74 * basic no-action implementation of processAll(). Two new virtual methods are
75 * added: processSetValues() and formatSingleValue().
76 * This leaves typeString(), convertValue() and formatStringValue() to be
77 * implemented in derived classes.
78 * processSetValues() and processAll() can also be implemented if necessary.
80 * Implements transaction support for adding values within a set: all calls to
81 * addValue() add the value to a temporary storage, processSetValues() operates
82 * on this temporary storage, and commitValues() then copies these values to
83 * the real storage. commitValues() provides a strong exception safety
84 * guarantee for the process (and it only throws if it runs out of memory).
87 * \ingroup module_options
90 class OptionStorageTemplate : public AbstractOptionStorage
93 //! Alias for the template class for use in base classes.
94 typedef OptionStorageTemplate<T> MyBase;
95 //! Type of the container that contains the current values.
96 typedef std::vector<T> ValueList;
98 // No implementation in this class for the pure virtual methods, but
99 // the declarations are still included for clarity.
100 // The various copydoc calls are needed with Doxygen 1.8.10, although
101 // things work without with 1.8.5...
102 std::string typeString() const override = 0;
103 //! \copydoc gmx::AbstractOptionStorage::valueCount()
104 int valueCount() const override { return store_->valueCount(); }
105 //! \copydoc gmx::AbstractOptionStorage::defaultValues()
106 std::vector<Any> defaultValues() const override;
107 /*! \copydoc gmx::AbstractOptionStorage::defaultValuesAsStrings()
109 * OptionStorageTemplate implements handling of defaultValueIfSet()
110 * cases and composing the vector.
111 * Derived classes must implement formatSingleValue() to provide the
112 * actual formatting for a value of type \p T.
114 std::vector<std::string> defaultValuesAsStrings() const override;
117 //! Smart pointer for managing the final storage interface.
118 typedef std::unique_ptr<IOptionValueStore<T>> StorePointer;
121 * Initializes the storage from option settings.
123 * \param[in] settings Option settings.
124 * \param[in] staticFlags Option flags that are always set and specify
125 * generic behavior of the option.
126 * \throws APIError if invalid settings have been provided.
129 explicit OptionStorageTemplate(const OptionTemplate<T, U>& settings,
130 OptionFlags staticFlags = OptionFlags());
132 * Initializes the storage from base option settings.
134 * \param[in] settings Option settings.
135 * \param[in] store Final storage location.
136 * \throws APIError if invalid settings have been provided.
138 * This constructor works for cases where there is no matching
139 * OptionTemplate (e.g., EnumOption).
141 OptionStorageTemplate(const AbstractOption& settings, StorePointer store);
143 //! \copydoc gmx::AbstractOptionStorage::clearSet()
144 void clearSet() override;
145 /*! \copydoc gmx::AbstractOptionStorage::convertValue()
147 * Derived classes should call addValue() after they have converted
148 * \p value to the storage type. It is allowed to call addValue()
149 * more than once, or not at all. OptionsAssigner::appendValue()
150 * provides the same exception safety guarantee as this method, so it
151 * should be considered whether the implementation can be made strongly
154 void convertValue(const Any& value) override = 0;
156 * Processes values for a set after all have been converted.
158 * \param[in,out] values Valid values in the set.
159 * \throws InvalidInputError if the values do not form a valid set.
161 * This method is called after all convertValue() calls for a set.
162 * \p values contains all values that were validly converted by
163 * convertValue(). The derived class may alter the values, but should
164 * in such a case ensure that a correct number of values is produced.
165 * If the derived class throws, all values in \p values are discarded.
167 virtual void processSetValues(ValueList* values) { GMX_UNUSED_VALUE(values); }
168 /*! \copydoc gmx::AbstractOptionStorage::processSet()
170 * OptionStorageTemplate implements transaction support for a set of
171 * values in this method (see the class description), and provides a
172 * more detailed processSetValues() method that can be overridden in
173 * subclasses to process the actual values. Derived classes should
174 * override that method instead of this one if set value processing is
177 void processSet() override;
178 /*! \copydoc gmx::AbstractOptionStorage::processAll()
180 * The implementation in OptionStorageTemplate does nothing.
182 void processAll() override {}
184 * Formats a single value as a string.
186 * \param[in] value Value to format.
187 * \returns \p value formatted as a string.
189 * The derived class must provide this method to format values a
190 * strings. Called by defaultValuesAsStrings() to do the actual
193 virtual std::string formatSingleValue(const T& value) const = 0;
196 * Adds a value to a temporary storage.
198 * \param[in] value Value to add. A copy is made.
199 * \throws std::bad_alloc if out of memory.
200 * \throws InvalidInputError if the maximum value count has been reached.
202 * Derived classes should call this function from the convertValue()
203 * implementation to add converted values to the storage.
204 * If the maximum value count has been reached, the value is discarded
205 * and an exception is thrown.
207 * If adding values outside convertValue() (e.g., to set a custom
208 * default value), derived classes should call clearSet() before adding
209 * values (unless in the constructor) and commitValues() once all
212 void addValue(const T& value);
214 * Commits values added with addValue().
216 * \throws std::bad_alloc if out of memory.
218 * If this function succeeds, values added with addValue() since the
219 * previous clearSet() are added to the storage for the option.
220 * Only throws in out-of-memory conditions, and provides the strong
221 * exception safety guarantee as long as the copy constructor of `T`
224 * See addValue() for cases where this method should be used in derived
227 * Calls clearSet() if it is successful.
232 * Sets the default value for the option.
234 * \param[in] value Default value to set.
235 * \throws std::bad_alloc if out of memory.
237 * This method can be used from the derived class constructor to
238 * programmatically set a default value.
240 void setDefaultValue(const T& value);
242 * Sets the default value if set for the option.
244 * \param[in] value Default value to set.
245 * \throws std::bad_alloc if out of memory.
247 * This method can be used from the derived class constructor to
248 * programmatically set a default value.
250 void setDefaultValueIfSet(const T& value);
253 * Provides derived classes access to the current list of values.
255 * The non-const any should only be used from processAll() in
256 * derived classes if necessary.
258 ArrayRef<T> values() { return store_->values(); }
259 //! Provides derived classes access to the current list of values.
260 ArrayRef<const T> values() const { return store_->values(); }
263 //! Creates the internal storage object for final values..
264 StorePointer createStore(ValueList* storeVector, T* store, int* storeCount, int initialCount);
267 * Vector for temporary storage of values before commitSet() is called.
269 ValueList setValues_;
270 //! Final storage for option values.
271 const StorePointer store_;
272 // This never releases ownership.
273 std::unique_ptr<T> defaultValueIfSet_;
275 // Copy and assign disallowed by base.
279 /*! \libinternal \brief
280 * Simplified option storage template for options that have one-to-one value
283 * \tparam T Assignable type that stores a single option value.
285 * To implement an option that always map a single input value to a single
286 * output value, derive from this class instead of OptionStorageTemplate.
287 * This class implements convertValue() in terms of two new virtual methods:
288 * initConverter() and processValue().
290 * To specify how different types of values need to be converted, implement
292 * To do common post-processing of the values after conversion, but before they
293 * are added to the underlying storage, override processValue().
296 * \ingroup module_options
299 class OptionStorageTemplateSimple : public OptionStorageTemplate<T>
302 //! Alias for the template class for use in base classes.
303 typedef OptionStorageTemplateSimple<T> MyBase;
306 //! Alias for the converter parameter type for initConverter().
307 typedef OptionValueConverterSimple<T> ConverterType;
309 //! Initializes the storage.
311 explicit OptionStorageTemplateSimple(const OptionTemplate<T, U>& settings,
312 OptionFlags staticFlags = OptionFlags()) :
313 OptionStorageTemplate<T>(settings, staticFlags), initialized_(false)
316 //! Initializes the storage.
317 OptionStorageTemplateSimple(const AbstractOption& settings,
318 typename OptionStorageTemplate<T>::StorePointer store) :
319 OptionStorageTemplate<T>(settings, std::move(store)), initialized_(false)
323 std::vector<Any> normalizeValues(const std::vector<Any>& values) const override
325 const_cast<MyBase*>(this)->ensureConverterInitialized();
326 std::vector<Any> result;
327 result.reserve(values.size());
328 for (const auto& value : values)
330 result.push_back(normalizeValue(converter_.convert(value)));
336 * Specifies how different types are converted.
338 * See OptionValueConverterSimple for more details.
340 virtual void initConverter(ConverterType* converter) = 0;
342 * Post-processes a value after conversion to the output type.
344 * \param[in] value Value after conversion.
345 * \returns Value to store for the option.
347 * The default implementation only provides an identity mapping.
349 virtual T processValue(const T& value) const { return value; }
351 * Converts a single value to normalized type.
353 * \param[in] value Value after conversion.
354 * \returns Value to store for the option.
356 * This can be overridden to serialize a different type than `T`
357 * when using the option with KeyValueTreeObject.
359 virtual Any normalizeValue(const T& value) const { return Any::create<T>(processValue(value)); }
362 void convertValue(const Any& any) override
364 ensureConverterInitialized();
365 this->addValue(processValue(converter_.convert(any)));
367 void ensureConverterInitialized()
371 initConverter(&converter_);
376 ConverterType converter_;
381 /********************************************************************
382 * OptionStorageTemplate implementation
387 OptionStorageTemplate<T>::OptionStorageTemplate(const OptionTemplate<T, U>& settings,
388 OptionFlags staticFlags) :
389 AbstractOptionStorage(settings, staticFlags),
390 store_(createStore(settings.storeVector_,
393 (settings.isVector() ? settings.maxValueCount_ : settings.minValueCount_)))
395 if (hasFlag(efOption_NoDefaultValue)
396 && (settings.defaultValue_ != nullptr || settings.defaultValueIfSet_ != nullptr))
398 GMX_THROW(APIError("Option does not support default value, but one is set"));
400 if (!hasFlag(efOption_NoDefaultValue))
402 setFlag(efOption_HasDefaultValue);
403 if (settings.defaultValue_ != nullptr)
405 setDefaultValue(*settings.defaultValue_);
407 if (settings.defaultValueIfSet_ != nullptr)
409 setDefaultValueIfSet(*settings.defaultValueIfSet_);
416 OptionStorageTemplate<T>::OptionStorageTemplate(const AbstractOption& settings, StorePointer store) :
417 AbstractOptionStorage(settings, OptionFlags()), store_(std::move(store))
423 std::unique_ptr<IOptionValueStore<T>> OptionStorageTemplate<T>::createStore(ValueList* storeVector,
425 int* storeCount, // NOLINT(readability-non-const-parameter) passed non-const to OptionValueStorePlain
428 if (storeVector != nullptr)
430 GMX_RELEASE_ASSERT(store == nullptr && storeCount == nullptr,
431 "Cannot specify more than one storage location");
432 return StorePointer(new OptionValueStoreVector<T>(storeVector));
434 else if (store != nullptr)
436 // If the maximum number of values is not known, storage to
437 // caller-allocated memory is unsafe.
438 if (maxValueCount() < 0 || hasFlag(efOption_MultipleTimes))
440 GMX_THROW(APIError("Cannot set user-allocated storage for arbitrary number of values"));
442 if (storeCount == nullptr && !isVector() && minValueCount() != maxValueCount())
445 APIError("Count storage is not set, although the number of produced values is "
448 if (hasFlag(efOption_NoDefaultValue))
452 return StorePointer(new OptionValueStorePlain<T>(store, storeCount, initialCount));
454 GMX_RELEASE_ASSERT(storeCount == nullptr, "Cannot specify count storage without value storage");
455 return StorePointer(new OptionValueStoreNull<T>());
460 std::vector<Any> OptionStorageTemplate<T>::defaultValues() const
462 std::vector<Any> result;
463 if (hasFlag(efOption_NoDefaultValue))
468 hasFlag(efOption_HasDefaultValue),
469 "Current option implementation can only provide default values before assignment");
470 for (const auto& value : values())
472 result.push_back(Any::create<T>(value));
474 return normalizeValues(result);
479 std::vector<std::string> OptionStorageTemplate<T>::defaultValuesAsStrings() const
481 std::vector<std::string> result;
482 if (hasFlag(efOption_NoDefaultValue))
487 hasFlag(efOption_HasDefaultValue),
488 "Current option implementation can only provide default values before assignment");
489 for (const auto& value : values())
491 result.push_back(formatSingleValue(value));
493 if (result.empty() || (result.size() == 1 && result[0].empty()))
496 if (defaultValueIfSet_ != nullptr)
498 result.push_back(formatSingleValue(*defaultValueIfSet_));
506 void OptionStorageTemplate<T>::clearSet()
513 void OptionStorageTemplate<T>::processSet()
515 processSetValues(&setValues_);
516 if (setValues_.empty() && defaultValueIfSet_ != nullptr)
518 addValue(*defaultValueIfSet_);
519 setFlag(efOption_HasDefaultValue);
523 clearFlag(efOption_HasDefaultValue);
525 if (!hasFlag(efOption_DontCheckMinimumCount)
526 && setValues_.size() < static_cast<size_t>(minValueCount()))
528 GMX_THROW(InvalidInputError("Too few (valid) values"));
535 void OptionStorageTemplate<T>::addValue(const T& value)
537 if (maxValueCount() >= 0 && setValues_.size() >= static_cast<size_t>(maxValueCount()))
539 GMX_THROW(InvalidInputError("Too many values"));
541 setValues_.push_back(value);
545 void OptionStorageTemplate<T>::commitValues()
547 if (hasFlag(efOption_ClearOnNextSet))
551 store_->reserve(setValues_.size());
552 // For bool the loop variable isn't a reference (it's its special reference type)
554 CLANG_DIAGNOSTIC_IGNORE(-Wrange-loop-analysis);
556 for (const auto& value : setValues_)
558 store_->append(value);
560 CLANG_DIAGNOSTIC_RESET;
565 void OptionStorageTemplate<T>::setDefaultValue(const T& value)
567 if (hasFlag(efOption_NoDefaultValue))
569 GMX_THROW(APIError("Option does not support default value, but one is set"));
571 if (hasFlag(efOption_HasDefaultValue))
573 setFlag(efOption_ExplicitDefaultValue);
575 store_->append(value);
581 void OptionStorageTemplate<T>::setDefaultValueIfSet(const T& value)
583 if (hasFlag(efOption_NoDefaultValue))
585 GMX_THROW(APIError("Option does not support default value, but one is set"));
587 if (hasFlag(efOption_MultipleTimes))
589 GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
591 setFlag(efOption_DefaultValueIfSetExists);
592 defaultValueIfSet_ = std::make_unique<T>(value);