diff options
author | Alexey Rusakov <Kitsune-Ral@users.sf.net> | 2022-05-08 17:43:08 +0200 |
---|---|---|
committer | Alexey Rusakov <Kitsune-Ral@users.sf.net> | 2022-05-08 17:43:58 +0200 |
commit | b79f67919e05698a8c3daffbe0fe53fa1ce46e54 (patch) | |
tree | e010db5f39d218dae7b5924576bf19b6706263f1 /lib/converters.h | |
parent | 72ffe9651fcdc3dfc0ceb34bd677aa15bbbe2ebf (diff) | |
download | libquotient-b79f67919e05698a8c3daffbe0fe53fa1ce46e54.tar.gz libquotient-b79f67919e05698a8c3daffbe0fe53fa1ce46e54.zip |
toSnakeCase and EventContent::SingleKeyValue
This is a rework of EventContent::SimpleContent previously defined in
simplestateevents.h. Quite a few events (and not only state events) have
just a single key-value pair in their content - this structure (which
is really just a template wrapper around the value) and the accompanying
JsonConverter<> specialisation encapsulate the concept to streamline
definition of such events. This commit only has simplestateevents.h
using it; further commits will use SingleKeyValue in other places.
toSnakeCase is a facility function that converts camelCase used for
C++ variables into snake_case used in JSON payloads. Combined with
the preprocessor trick that makes a string literal from an identifier,
this allows to reduce boilerplate code that repeats the same name for
fields in C++ event classes and fields in JSON. SingleKeyValue uses it,
and there are other cases for it coming.
Diffstat (limited to 'lib/converters.h')
-rw-r--r-- | lib/converters.h | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/lib/converters.h b/lib/converters.h index 515c96fd..6515310a 100644 --- a/lib/converters.h +++ b/lib/converters.h @@ -414,4 +414,20 @@ inline void addParam(ContT& container, const QString& key, ValT&& value) _impl::AddNode<std::decay_t<ValT>, Force>::impl(container, key, std::forward<ValT>(value)); } + +// This is a facility function to convert camelCase method/variable names +// used throughout Quotient to snake_case JSON keys - see usage in +// single_key_value.h and event.h (DEFINE_CONTENT_GETTER macro). +inline auto toSnakeCase(QLatin1String s) +{ + QString result { s }; + for (auto it = result.begin(); it != result.end(); ++it) + if (it->isUpper()) { + const auto offset = static_cast<int>(it - result.begin()); + result.insert(offset, '_'); // NB: invalidates iterators + it = result.begin() + offset + 1; + *it = it->toLower(); + } + return result; +} } // namespace Quotient |