Files
externals/linux/include/ActivMiddleware/ActivBase/IniFileParser.h
T
2023-12-15 13:15:08 -05:00

1236 lines
39 KiB
C++

/**
* @file include/ActivMiddleware/ActivBase/IniFileParser.h
*
* @brief Header file for ini file parser class.
*/
#if (!defined ACTIV_BASE_INI_FILE_PARSER_H)
#define ACTIV_BASE_INI_FILE_PARSER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Exception.h"
#include "ActivMiddleware/ActivBase/FieldTypes/ActivFieldTypes.h"
#include "ActivMiddleware/Misc/FunctionObjects.h"
#include "ActivMiddleware/Misc/Optional.h"
#include "ActivMiddleware/Misc/SerializableContainerHelper.h"
#include "ActivMiddleware/Misc/TemplateFunctions.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(algorithm/string/split.hpp)
#include ACTIV_BOOST_INCLUDE(algorithm/string/classification.hpp)
#include ACTIV_BOOST_INCLUDE(numeric/conversion/cast.hpp)
#include ACTIV_BOOST_INCLUDE(optional/optional.hpp)
#include ACTIV_BOOST_INCLUDE(range/adaptor/map.hpp)
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#include ACTIV_BOOST_INCLUDE(utility/enable_if.hpp)
#include <vector>
#include <typeinfo>
//! Activ namespace.
namespace Activ
{
class MessageBuilder;
class MessageValidator;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Throw an IniFileParser::AccessorException object with information about the location of the throw site.
*
* @param a an object providing a MakeException() function that returns an IniFileParser::AccessorException.
* @param r a textual reason to give for the exception.
*/
#define ACTIV_THROW_INI_FILE_EXCEPTION(a, r) ACTIV_BOOST_THROW_EXCEPTION((a).MakeException((r)))
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ini file parser.
*
* Note all section and key searches are case insensitive.
*/
class IniFileParser
{
private:
typedef std::pair<String, String> Key; ///< Key is pair<name, value>.
typedef std::vector<Key> KeyList; ///< List of keys.
typedef std::pair<String, KeyList> Section; ///< Section is pair<name, list of keys>.
typedef std::vector<Section> SectionList; ///< Ini file is a list of sections.
public:
//! Exception generated by parse errors.
class ParseException : public Exception
{
public:
/**
* @brief Constructor.
*
* @param file
* @param function
* @param line
* @param offset
* @param validPart
* @param iniFileName
*/
ACTIV_BASE_API ParseException(const char *file, const char *function, const uint_fast32_t line,
const size_t offset, const String &validPart, const String &iniFileName);
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
const size_t m_offset; ///< Offset in the file where parsing failed.
const String m_validPart; ///< Parsing failed at end of this.
const String m_iniFileName; ///< File where parsing failed.
};
/**
* @brief Exception thrown when a mandatory key or section is missing, or when a value is an invalid format, or
* optionally thrown by the user as and when required.
*
* This exception class can be tagged, using Boost::exception's << operator, with information about the
* ini-file, section, key, value in question. For example:
*
* AccessorException accessorException("something went awry");
* accessorException << AccessorException::FileNameInfo("config.ini");
* throw accessorException;
*
* The ACTIV_THROW_INI_FILE_EXCEPTION macro is provided for generating and throwing an AccessorException from an
* Accessor object with useful context.
*/
class AccessorException : public virtual Boost::exception, public virtual std::exception
{
public:
typedef Boost::error_info<class FilenameTag, String> FileNameInfo;
typedef Boost::error_info<class SectionTag, String> SectionInfo;
typedef Boost::error_info<class KeyTag, String> KeyInfo;
typedef Boost::error_info<class ValueTag, String> ValueInfo;
/**
* @brief Constructor.
*
* @param reasonString a textual reason for the exception.
*/
ACTIV_BASE_API AccessorException(const String &reasonString);
//! Destructor.
ACTIV_BASE_API ~AccessorException() throw();
// std::exception overrides.
ACTIV_BASE_API virtual const char *what() const throw() ACTIV_OVERRIDE;
private:
const String m_reasonString;
};
//! Alias map helper.
template<typename T>
class AliasMapHelper
{
public:
typedef std::map<String, T, CaseInsensitiveLessThanStringComparisonObject<> > type;
};
static const char SECTION_DELIMITER = ':'; ///< Sub-sections are delimited with this, eg [Section:SubSection].
static const size_t MATCH_LENGTH_COMPLETE = Boost::integer_traits<size_t>::const_max;
// Forward reference of section iterator.
class ConstSectionIterator;
// Forward reference of Accessor template.
template<bool>
class Accessor;
//! Const iterator to section keys.
class ConstKeyIterator
{
public:
/**
* @brief Generate an exception ready for throwing with information about this key.
*
* @param reasonString textual reason to pass in the exception.
*
* @return AccessorException
*/
ACTIV_BASE_API const AccessorException MakeException(const String &reasonString) const;
/**
* @brief Get the key name.
*
* @return The key name.
*/
ACTIV_BASE_API const String GetName() const;
/**
* @brief Advance to the next key in the section.
*
* @return *this.
*/
ACTIV_BASE_API ConstKeyIterator &operator++();
/**
* @brief Equality operator.
*
* @param rhs KeyIterator to compare to.
*
* @return boolean.
*/
ACTIV_BASE_API bool operator==(const ConstKeyIterator &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs KeyIterator to compare to.
*
* @return boolean.
*/
ACTIV_BASE_API bool operator!=(const ConstKeyIterator &rhs) const;
private:
/**
* @brief Constructor.
*
* @param iniFileParser
* @param section section the key is in.
* @param iterator underlying iterator to key.
* @param matchLength length of section name to match on when advancing.
*/
ConstKeyIterator(const IniFileParser &iniFileParser,
const SectionList::const_iterator &sectionIterator, const KeyList::const_iterator &iterator, const size_t matchLength);
const IniFileParser & m_iniFileParser; ///< Inifile this key is in.
SectionList::const_iterator m_sectionIterator; ///< Section the key is in.
KeyList::const_iterator m_iterator; ///< Underlying stl iterator.
const size_t m_matchLength; ///< Length to match on, or all.
friend class IniFileParser;
friend class ConstSectionIterator;
friend class Accessor<true>;
friend class Accessor<false>;
};
//! Const iterator to ini file sections.
class ConstSectionIterator
{
public:
/**
* @brief Generate an exception ready for throwing with information about this section.
*
* @param reasonString textual reason to pass in the exception.
*
* @return AccessorException
*/
ACTIV_BASE_API const AccessorException MakeException(const String &reasonString) const;
/**
* @brief Get the complete name of the section.
*
* @return The section name.
*/
ACTIV_BASE_API const String &GetName() const;
/**
* @brief Get just the sub section name (for a top level section this == GetName()).
*
* @return The sub section name.
*/
ACTIV_BASE_API const String GetSubName() const;
/**
* @brief Get an iterator to the first key in the section. If there are no keys, will equal
* EndKey().
*
* @return Iterator to the first key in this section.
*/
ACTIV_BASE_API const ConstKeyIterator BeginOptionalKey() const;
/**
* @brief Get an iterator to the first key in the section.
*
* @return Iterator to the first key in this section.
*
* @throw AccessorException if there are no keys in this section.
*/
ACTIV_BASE_API const ConstKeyIterator BeginMandatoryKey() const;
/**
* @brief Get an iterator to past the last key in the section.
*
* @return Iterator to past the last key in the section.
*/
ACTIV_BASE_API const ConstKeyIterator EndKey() const;
/**
* @brief Find a key by name.
*
* @param keyName key to find.
* @param matchLength how much of @a keyName to match on. Default is complete match
*
* @return Iterator to the key. Will equal EndKey() if not found.
*/
ACTIV_BASE_API const ConstKeyIterator FindOptionalKey(const String &keyName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Find a key by name.
*
* @param keyName key to find.
* @param matchLength how much of @a keyName to match on. Default is complete match
*
* @return Iterator to the key.
*
* @throw AccessorException if not found.
*/
ACTIV_BASE_API const ConstKeyIterator FindMandatoryKey(const String &keyName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Get an iterator to the first sub section in the section.
*
* @return Iterator to the first sub section in the section. If the section contains no sub-sections,
* will be equal to EndSubSection().
*/
ACTIV_BASE_API const ConstSectionIterator BeginOptionalSubSection() const;
/**
* @brief Get an iterator to the first sub section in the section.
*
* @return Iterator to the first sub section in the section.
*
* @throw AccessorException if the section contains no sub-sections.
*/
ACTIV_BASE_API const ConstSectionIterator BeginMandatorySubSection() const;
/**
* @brief Get an iterator to past the last sub section in the section.
*
* @return Iterator to past the last sub section in the section.
*/
ACTIV_BASE_API const ConstSectionIterator EndSubSection() const;
/**
* @brief Find an optional sub section of this section. Sub section names are delimited with sectionDelimiter.
*
* @param subSectionName name of the sub section.
* @param matchLength how much of @a subSectionName to match on. Default is complete match
*
* @return Iterator to sub section or EndSection() if not found.
*/
ACTIV_BASE_API const ConstSectionIterator FindOptionalSubSection(const String &subSectionName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Find a sub section of this section. Sub section names are delimited with sectionDelimiter.
*
* @param subSectionName name of the sub section.
* @param matchLength how much of @a subSectionName to match on. Default is complete match
*
* @return Iterator to sub section.
*
* @throw AccessorException if not found.
*/
ACTIV_BASE_API const ConstSectionIterator FindMandatorySubSection(const String &subSectionName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Get an iterator to past the last section in the ini file.
*
* @return Iterator to past the last section in the ini file.
*/
ACTIV_BASE_API const ConstSectionIterator EndSection() const;
/**
* @brief Advance to the next section in the ini file.
*
* @return *this.
*/
ACTIV_BASE_API ConstSectionIterator &operator++();
/**
* @brief Equality operator.
*
* @param rhs SectionIterator to compare to.
*
* @return boolean.
*/
ACTIV_BASE_API bool operator==(const ConstSectionIterator &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs SectionIterator to compare to.
*
* @return boolean.
*/
ACTIV_BASE_API bool operator!=(const ConstSectionIterator &rhs) const;
//! Get ini file parser.
ACTIV_BASE_API const IniFileParser &GetIniFileParser() const;
private:
/**
* @brief Constructor.
*
* @param iniFileParser ini file the section is in.
* @param iterator underlying iterator to key.
* @param matchLength length of section name to match on when advancing.
*/
ConstSectionIterator(const IniFileParser &iniFileParser, const SectionList::const_iterator &iterator,
const size_t matchLength);
const IniFileParser & m_iniFileParser; ///< Inifile this section is in.
SectionList::const_iterator m_iterator; ///< Underlying stl iterator.
const size_t m_matchLength; ///< Length to match on, or all.
friend class IniFileParser;
friend class Accessor<true>;
friend class Accessor<false>;
};
/**
* @brief Class to access key values.
*
* MANDATORY specify true to throw an exception if a section or key isn't found.
*/
template<bool MANDATORY>
class Accessor
{
public:
/**
* @brief Constructor to access a key's value directly.
*
* @param keyIterator iterator to a key that has already been found.
*/
ACTIV_BASE_API Accessor(const ConstKeyIterator &keyIterator);
/**
* @brief Constructor to access a key's value from a section iterator and a key name.
*
* @param sectionIterator iterator to a section that has already been found.
* @param keyName the name of the key to find the value of.
*
* @throw AccessorException if MANDATORY is true and @a keyName is not found in the section iterated to by @
* sectionIterator.
*/
ACTIV_BASE_API Accessor(const ConstSectionIterator &sectionIterator, const String &keyName);
/**
* @brief Constructor to access a key's value from an IniFileParser, section name and key name.
*
* @param iniFileParser
* @param sectionName the name of the section to find the key in.
* @param keyName the name of the key to find the value of.
*
* @throw AccessorException if MANDATORY is true and @a sectionName is not found in the @a iniFileParser, or
* keyName is not found in the section.
*/
ACTIV_BASE_API Accessor(const IniFileParser &iniFileParser, const String &sectionName,
const String &keyName);
/**
* @brief Generate an exception ready for throwing with information about an access failure.
*
* Can be used as follows:
*
* IniFileParser::Accessor<true> myValueAccessor(iniFileParser, "MySection", MyValue);
* uint32_t someValue;
* myValueAccessor(someValue);
* // Additional user-level validation.
* if ((someValue > 10) || (someValue < 20))
* ACTIV_THROW_INI_FILE_EXCEPTION(myValueAccessor, "can't be between 10 and 20");
*
* @param reasonString textual reason for the access failure.
*
* @return AccessorException
*/
ACTIV_BASE_API const AccessorException MakeException(const String &reasonString) const;
/**
* @brief Get string value for this key.
*
* @param value reference to a string variable to receive the value.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*/
ACTIV_BASE_API bool operator()(String &value) const;
/**
* @brief Get a list of string values for this key.
*
* @param valueContainer reference to a container to append the strings to.
* @param delimiterList list of valid value delimiter characters.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate for type C::value_type.
*/
template<typename C>
typename Boost::enable_if_c<
(Boost::is_same<typename C::value_type, String>::value && !IsOptional<C>::value), bool>::type
operator()(C &valueContainer, const String &delimiterList = String(",")) const
{
if (!m_pKeyIterator)
return false;
Boost::algorithm::split(valueContainer, m_pKeyIterator->m_iterator->second, Boost::is_any_of(delimiterList),
Boost::token_compress_on);
return true;
}
/**
* @brief Get a value for this key (signed, unsigned, floating point or Activ field type).
*
* @param value reference to a variable to receive the value.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::disable_if_c<(has_type_iterator<T>::value || IsOptional<T>::value), bool>::type
operator()(T &value) const
{
ACTIV_BOOST_STATIC_ASSERT_MSG(!Boost::is_enum<T>::value,
"enumerations are only supported in conjuction with an aliasmap");
ACTIV_BOOST_STATIC_ASSERT_MSG((Boost::mpl::or_<Boost::is_arithmetic<T>, IsFieldType<T> >::value), "unsupported type");
if (!m_pKeyIterator)
return false;
try
{
value = GetSingleValueWrapper<T>(m_pKeyIterator->m_iterator->second);
}
catch (const String &exception)
{
throw MakeException(exception);
}
return true;
}
/**
* @brief Get a value for this key (signed, unsigned, floating point, enum or Activ field type).
*
* @param value reference to a variable to receive the value.
* @param aliasMap a map of string to value aliases.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::disable_if_c<(has_type_iterator<T>::value || IsOptional<T>::value), bool>::type
operator()(T &value, const typename AliasMapHelper<T>::type &aliasMap) const
{
typedef typename AliasMapHelper<T>::type ALIAS_MAP_TYPE;
ACTIV_BOOST_STATIC_ASSERT_MSG((Boost::mpl::or_<Boost::is_arithmetic<T>, Boost::is_enum<T>, IsFieldType<T> >::value),
"unsupported type");
if (!m_pKeyIterator)
return false;
try
{
value = GetSingleValueWrapperWithAliasMap<T, ALIAS_MAP_TYPE>(m_pKeyIterator->m_iterator->second, aliasMap);
}
catch (const String &exception)
{
throw MakeException(exception);
}
return true;
}
/**
* @brief Get a list of values for this key (signed, unsigned, floating point or Activ field type).
*
* @param valueContainer reference to a container to append the values to.
* @param delimiterList list of valid value delimiter characters.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate for type C::value_type.
*/
template<typename C>
typename Boost::disable_if_c<
(Boost::is_same<typename C::value_type, String>::value ||
Boost::is_same<C, String>::value ||
IsOptional<C>::value), bool>::type
operator()(C &valueContainer, const String &delimiterList = String(",")) const
{
typedef typename C::value_type TYPE;
ACTIV_BOOST_STATIC_ASSERT_MSG(!Boost::is_enum<TYPE>::value,
"enumerations are only supported in conjunction with an aliasmap");
ACTIV_BOOST_STATIC_ASSERT_MSG((Boost::mpl::or_<Boost::is_arithmetic<TYPE>, IsFieldType<TYPE> >::value),
"unsupported type");
std::vector<String> stringList;
if (!this->operator()(stringList, delimiterList))
return false;
try
{
GetMultipleValues(stringList, valueContainer, CxxYZ::bind(&IniFileParser::GetSingleValueWrapper<TYPE>, CxxYZ::_1));
}
catch (const String &exception)
{
throw MakeException(exception + " ('" + delimiterList + "' separated list)");
}
return true;
}
/**
* @brief Get a list of values for this key (signed, unsigned, floating point, enum or Activ field type).
*
* @param valueContainer reference to a container to append the values to.
* @param aliasMap a map of string to value aliases.
* @param delimiterList list of valid value delimiter characters.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate for type C::value_type.
*/
template<typename C>
typename Boost::disable_if_c<
(Boost::is_same<typename C::value_type, String>::value ||
Boost::is_same<C, String>::value ||
IsOptional<C>::value), bool>::type
operator()(C &valueContainer, const typename AliasMapHelper<typename C::value_type>::type &aliasMap,
const String &delimiterList = String(",")) const
{
typedef typename C::value_type TYPE;
typedef typename AliasMapHelper<TYPE>::type ALIAS_MAP_TYPE;
ACTIV_BOOST_STATIC_ASSERT_MSG((Boost::mpl::or_<Boost::is_arithmetic<TYPE>, Boost::is_enum<TYPE>,
IsFieldType<TYPE> >::value), "unsupported type");
std::vector<String> stringList;
if (!this->operator()(stringList, delimiterList))
return false;
try
{
GetMultipleValues(stringList, valueContainer,
CxxYZ::bind(&IniFileParser::GetSingleValueWrapperWithAliasMap<TYPE, ALIAS_MAP_TYPE>, CxxYZ::_1,
CxxYZ::cref(aliasMap)));
}
catch (const String &exception)
{
throw MakeException(exception + " ('" + delimiterList + "' separated list)");
}
return true;
}
/**
* @brief Get boolean value for this key.
*
* @param value reference to a boolean variable to receive the value.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found.
*
* @throw AccessorException if the key's value is not in a format appropriate to be read as a boolean type.
*/
ACTIV_BASE_API bool operator()(bool &value) const;
/**
* @brief Get a value for this key.
*
* @param value reference to a Boost::optional variable to receive the value.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found. If the value was not
* found and the optional value was initially initialized, it is not reset to the uninitialized state.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::disable_if<has_type_iterator<T>, bool>::type operator()(Boost::optional<T> &value) const
{
// emplace and/or move support would be nice!
if (value)
{
return operator()(*value);
}
else
{
T newValue;
if (!operator()(newValue))
return false;
value = newValue;
return true;
}
}
/**
* @brief Get a value for this key.
*
* @param value reference to a Boost::optional variable to receive the value.
* @param aliasMap a map of string to value aliases.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found. If the value was not
* found and the optional value was initially initialized, it is not reset to the uninitialized state.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::disable_if<has_type_iterator<T>, bool>::type operator()(Boost::optional<T> &value,
const typename AliasMapHelper<T>::type &aliasMap) const
{
// emplace and/or move support would be nice!
if (value)
{
return operator()(*value, aliasMap);
}
else
{
T newValue;
if (!operator()(newValue, aliasMap))
return false;
value = newValue;
return true;
}
}
/**
* @brief Get a list of values for this key.
*
* @param value reference to a Boost::optional variable to receive the value.
* @param delimiterList list of valid value delimiter characters.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found. If the value was not
* found and the optional value was initially initialized, it is not reset to the uninitialized state.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::enable_if<has_type_iterator<T>, bool>::type operator()(Boost::optional<T> &value,
const String &delimiterList = String(",")) const
{
// emplace and/or move support would be nice!
if (value)
{
return operator()(*value, delimiterList);
}
else
{
T newValue;
if (!operator()(newValue, delimiterList))
return false;
value = newValue;
return true;
}
}
/**
* @brief Get a list of values for this key.
*
* @param value reference to a Boost::optional variable to receive the value.
* @param aliasMap a map of string to value aliases.
* @param delimiterList list of valid value delimiter characters.
*
* @return true if the value was read; false if MANDATORY is false and the value was not found. If the value was not
* found and the optional value was initially initialized, it is not reset to the uninitialized state.
*
* @throw AccessorException if the key's value is not in a format appropriate for type T.
*/
template<typename T>
typename Boost::enable_if<has_type_iterator<T>, bool>::type operator()(Boost::optional<T> &value,
const typename AliasMapHelper<typename T::value_type>::type &aliasMap, const String &delimiterList = String(",")) const
{
// emplace and/or move support would be nice!
if (value)
{
return operator()(*value, aliasMap, delimiterList);
}
else
{
T newValue;
if (!operator()(newValue, aliasMap, delimiterList))
return false;
value = newValue;
return true;
}
}
private:
const IniFileParser & m_iniFileParser;
const String m_sectionName;
const String m_keyName;
Boost::scoped_ptr<ConstSectionIterator> m_pSectionIterator;
Boost::scoped_ptr<ConstKeyIterator> m_pKeyIterator;
};
typedef Accessor<true> MandatoryAccessor; ///< Handy typedef for a mandatory value accessor.
typedef Accessor<false> OptionalAccessor; ///< Handy typedef for an optional value accessor.
/**
* @brief Constructor to find a key from a section iterator and a key name.
*
* @param sectionIterator iterator to a section that has already been found.
* @param keyName the name of the key to find.
* @param reason the reason this key is no longer valid.
*
* @throw AccessorException if @a keyName is found in the section iterated to by @ sectionIterator.
*/
ACTIV_BASE_API static void InvalidAccessor(const ConstSectionIterator &sectionIterator, const String &keyName,
const String &reason);
/**
* @brief Constructor to find a key from an IniFileParser, section name and key name.
*
* @param iniFileParser
* @param sectionName the name of the section to find the key in.
* @param keyName the name of the key to find.
* @param reason the reason this key is no longer valid.
*
* @throw AccessorException if @a sectionName is found in the @a iniFileParser or keyName is found in the section.
*/
ACTIV_BASE_API static void InvalidAccessor(const IniFileParser &iniFileParser, const String &sectionName,
const String &keyName, const String &reason);
//! Default constructor.
ACTIV_BASE_API IniFileParser();
/**
* @brief Constructor. Parses the ini file.
*
* @param iniFileName ini file to parse.
*
* @throw StatusCodeException
* @throw ParseException
*/
ACTIV_BASE_API IniFileParser(const String &iniFileName);
/**
* @brief Constructor. Parses an ini file from a buffer.
*
* @param pBuffer pointer to the buffer.
* @param bufferLength the length of the buffer.
*
* @throw StatusCodeException
* @throw ParseException
*/
ACTIV_BASE_API IniFileParser(const byte_t * const pBuffer, const size_t bufferLength);
//! Destructor.
ACTIV_BASE_API ~IniFileParser();
/**
* @brief Generate an exception ready for throwing with information about this ini file.
*
* @param reasonString textual reason to pass in the exception.
*
* @return AccessorException
*/
ACTIV_BASE_API const AccessorException MakeException(const String &reasonString) const;
/**
* @brief Get an iterator to the first section in the ini file.
*
* @return Iterator to the first section in the ini file. If the ini file contains no sections, will be
* equal to EndSection().
*/
ACTIV_BASE_API const ConstSectionIterator BeginOptionalSection() const;
/**
* @brief Get an iterator to the first section in the ini file.
*
* @return Iterator to the first section in the ini file.
*
* @throw AccessorException if the ini file contains no sections.
*/
ACTIV_BASE_API const ConstSectionIterator BeginMandatorySection() const;
/**
* @brief Get an iterator to past the last section in the ini file.
*
* @return Iterator to past the last section in the ini file.
*/
ACTIV_BASE_API const ConstSectionIterator EndSection() const;
/**
* @brief Find an optional section in the ini file by name.
*
* @param sectionName name of the section name to find.
* @param matchLength how much of @a sectionName to match on. Default is complete match
*
* @return Iterator to the section. Will equal EndSection() if the section doesn't exist.
*/
ACTIV_BASE_API const ConstSectionIterator FindOptionalSection(const String &sectionName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Find a section in the ini file by name.
*
* @param sectionName name of the section name to find.
* @param matchLength how much of @a sectionName to match on. Default is complete match
*
* @return Iterator to the section.
*
* @throw AccessorException if the section does not exist.
*/
ACTIV_BASE_API const ConstSectionIterator FindMandatorySection(const String &sectionName,
const size_t matchLength = MATCH_LENGTH_COMPLETE) const;
/**
* @brief Serialize to a MessageBuilder.
*
* @param messageBuilder to serialize into.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
ACTIV_BASE_API StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize from a MessageValidator into this object.
*
* @param messageValidator to deserialize from.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
ACTIV_BASE_API StatusCode Deserialize(MessageValidator &messageValidator);
/**
* @brief Build a section name from a list of sub-section names.
*
* @param count the count of sub-sections.
* @param ... list of @a count sub-section names of type const char *.
*
* @return the section name in the form A:B:C.
*/
ACTIV_BASE_API static const String GetSectionName(const size_t count, ...);
//! Get ini file name.
ACTIV_BASE_API const String &GetIniFileName() const;
class Grammar;
private:
//! Section serializer class.
class SectionSerializer
{
public:
/**
* @brief Serialize a Section to a MessageBuilder.
*
* @param messageBuilder to serialize into.
* @param section to serialize.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
static StatusCode Serialize(MessageBuilder &messageBuilder, const Section &section);
/**
* @brief Deserialize from a MessageValidator into a Section.
*
* @param messageValidator to deserialize from.
* @param section to deserialize into.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
static StatusCode Deserialize(MessageValidator &messageValidator, Section &section);
};
//! Key serializer class.
class KeySerializer
{
public:
/**
* @brief Serialize a Key to a MessageBuilder.
*
* @param messageBuilder to serialize into.
* @param key to serialize.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
static StatusCode Serialize(MessageBuilder &messageBuilder, const Key &key);
/**
* @brief Deserialize from a MessageValidator into a Key.
*
* @param messageValidator to deserialize from.
* @param key to deserialize into.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
static StatusCode Deserialize(MessageValidator &messageValidator, Key &key);
};
//! Normalize the section list such that sub-sections always have a parent (sub-)section.
void Normalize();
/**
* @brief Get single value (unsigned).
*
* @param valueString the string representation of an unsigned integer.
*
* @return the value.
*
* @throw String
*/
template<typename T>
static typename Boost::enable_if_c<(Boost::is_unsigned<T>::value && !Boost::is_enum<T>::value), T>::type
GetSingleValue(const String &valueString)
{
MessageValidator messageValidator(valueString.c_str(), valueString.length());
T tempValue;
const StatusCode statusCode = messageValidator.ValidateUnsignedAsciiIntegral(messageValidator.GetLength(), tempValue);
if (STATUS_CODE_SUCCESS == statusCode)
return tempValue;
throw String(StatusCodeToString(statusCode) + " - expected unsigned int");
}
/**
* @brief Get single value (signed).
*
* @param valueString the string representation of an signed integer.
*
* @return the value.
*
* @throw String
*/
template<typename T>
static typename Boost::enable_if_c<(Boost::is_signed<T>::value && !Boost::is_enum<T>::value &&
!Boost::is_same<T, char>::value), T>::type
GetSingleValue(const String &valueString)
{
MessageValidator messageValidator(valueString.c_str(), valueString.length());
T tempValue;
const StatusCode statusCode = messageValidator.ValidateSignedAsciiIntegral(messageValidator.GetLength(), tempValue);
if (STATUS_CODE_SUCCESS == statusCode)
return tempValue;
throw String(StatusCodeToString(statusCode) + " - expected int");
}
/**
* @brief Get single value (enum, always throws).
*
* @param valueString the string representation of an signed integer.
*
* @throw String
*/
template<typename T>
static typename Boost::enable_if<Boost::is_enum<T>, T>::type GetSingleValue(const String &valueString)
{
throw String(StatusCodeToString(STATUS_CODE_INVALID_FORMAT) + " - expected");
#if (defined ACTIV_COMPILER_SUNPRO)
// To silence sun compiler.
return static_cast<T>(0);
#endif
}
/**
* @brief Get single value (float).
*
* @param valueString the string representation of a value.
*
* @return the value.
*
* @throw String
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_BASE_API) static typename Boost::enable_if<Boost::is_float<T>, T>::type GetSingleValue(
const String &valueString);
/**
* @brief Get single value (char).
*
* @param valueString the string representation of a value.
*
* @return the value.
*
* @throw String
*/
template<typename T>
static typename Boost::enable_if<Boost::is_same<T, char>, T>::type GetSingleValue(const String &valueString)
{
MessageValidator messageValidator(valueString.c_str(), valueString.length());
T tempValue;
const StatusCode statusCode = messageValidator.ValidateBinaryIntegralRange<sizeof(char), MessageValidator::ENDIAN_LITTLE,
char, MessageValidator::MIN_PRINTABLE_ASCII, MessageValidator::MAX_PRINTABLE_ASCII>(tempValue);
if ((STATUS_CODE_SUCCESS == statusCode) && messageValidator.IsEndOfMessage())
return tempValue;
throw String(StatusCodeToString(STATUS_CODE_INVALID_FORMAT) + " - expected char");
}
/**
* @brief Get single value (Activ field type).
*
* @param valueString the string representation of a value.
*
* @return the value.
*
* @throw String
*/
template<typename T>
static typename Boost::enable_if<IsFieldType<T>, T>::type GetSingleValue(const String &valueString)
{
MessageValidator messageValidator(valueString.c_str(), valueString.length());
T tempValue;
const StatusCode statusCode = tempValue.FromString(messageValidator);
if (STATUS_CODE_SUCCESS == statusCode)
return tempValue;
throw String(StatusCodeToString(STATUS_CODE_INVALID_FORMAT) + " - expected " + tempValue.GetFromStringFormat());
}
/**
* @brief Get single value wrapper (forward to appropriate function).
*
* @param valueString the string representation of a value.
* @param aliasMap a map of string to value aliases.
*
* @return the value.
*
* @throw String
*/
template<typename T>
static T GetSingleValueWrapper(const String &valueString)
{
// This wrapper is needed rather than binding to GetSingleValue directly as GCC couldn't work out which one to use.
return GetSingleValue<T>(valueString);
}
/**
* @brief Get single value (from the alias map or forward to appropriate function).
*
* @param valueString the string representation of a value.
* @param aliasMap a map of string to value aliases.
*
* @return the value.
*
* @throw String
*/
template<typename T, typename M>
static T GetSingleValueWrapperWithAliasMap(const String &valueString, const M &aliasMap)
{
typename M::const_iterator iterator = aliasMap.find(valueString);
if (aliasMap.end() != iterator)
return iterator->second;
try
{
return GetSingleValue<T>(valueString);
}
catch (const String &exception)
{
if (Boost::is_enum<T>::value)
{
throw String(exception + " " + StringRangeToString(Boost::adaptors::keys(aliasMap), " or"));
}
else
{
throw String(exception + " or " + StringRangeToString(Boost::adaptors::keys(aliasMap), " or"));
}
}
}
/**
* @brief Get multiple values (integer).
*
* @param stringList a list of strings to parse.
* @param valueContainer containter to insert the strings into.
* @param conversionFunction function to use for string to value conversion.
*
* @throw StatusCodeException
*/
template<typename C, typename F>
static typename Boost::enable_if<Boost::is_integral<typename C::value_type>, void>::type
GetMultipleValues(const std::vector<String> &stringList, C &valueContainer, F getSingleValueFunction)
{
typedef typename C::value_type TYPE;
for (std::vector<String>::const_iterator iter = stringList.begin(), iterEnd = stringList.end(); iter != iterEnd; ++iter)
{
const String &token = *iter;
if (token.empty())
continue;
// Could be a range of values (N-M).
// N or M may be negative so skip the first char, the next occurence must be the range separator.
const size_t rangeSeparatorPosition = token.find('-', 1);
if (String::npos != rangeSeparatorPosition)
{
TYPE startValue = getSingleValueFunction(token.substr(0, rangeSeparatorPosition));
TYPE endValue = getSingleValueFunction(token.substr(rangeSeparatorPosition + 1));
// Convert a descending range to ascending.
if (startValue <= endValue)
{
for (; startValue <= endValue; ++startValue)
valueContainer.insert(valueContainer.end(), startValue);
}
else
{
for (; startValue >= endValue; --startValue)
valueContainer.insert(valueContainer.end(), startValue);
}
}
else
{
const TYPE value = getSingleValueFunction(token);
valueContainer.insert(valueContainer.end(), value);
}
}
}
/**
* @brief Get multiple values (not integer).
*
* @param stringList a list of strings to parse.
* @param valueContainer containter to insert the strings into.
* @param getSingleValueFunction function to use for string to value conversion.
*
* @throw StatusCodeException
*/
template<typename C, typename F>
static typename Boost::disable_if<Boost::is_integral<typename C::value_type>, void>::type
GetMultipleValues(const std::vector<String> &stringList, C &valueContainer, F getSingleValueFunction)
{
typedef typename C::value_type TYPE;
for (std::vector<String>::const_iterator iter = stringList.begin(), iterEnd = stringList.end(); iter != iterEnd; ++iter)
{
const String &token = *iter;
if (token.empty())
continue;
const TYPE value = getSingleValueFunction(token);
valueContainer.insert(valueContainer.end(), value);
}
}
//! Section list (de)serializer.
typedef SerializableContainerHelper<SectionList, uint32_t, 0, UINT32_MAX, SectionSerializer> SectionListSerializer;
//! Key list (de)serializer.
typedef SerializableContainerHelper<KeyList, uint32_t, 0, UINT32_MAX, KeySerializer> KeyListSerializer;
String m_fileName;
SectionList m_sectionList; ///< Parsed list of sections.
};
} // namepsace Activ
#endif // (!defined ACTIV_BASE_INI_FILE_PARSER_H)