xref: /aosp_15_r20/external/executorch/backends/apple/coreml/runtime/kvstore/json_key_value_store.hpp (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 //
2 // JSONKeyValueStore.h
3 //
4 // Copyright © 2024 Apple Inc. All rights reserved.
5 //
6 // Please refer to the license found in the LICENSE file in the root directory of the source tree.
7 
8 #pragma once
9 
10 #include <key_value_store.hpp>
11 
12 #include <iostream>
13 #include <sstream>
14 
15 namespace executorchcoreml {
16 namespace sqlite {
17 
18 /// Returns string from `sqlite::UnOwnedValue`
19 ///
20 /// The method fails if the `value` does not contain `UnOwnedString`.
21 ///
22 /// @param value The unowned value.
23 /// @retval The string.
24 std::string string_from_unowned_value(const sqlite::UnOwnedValue& value);
25 
26 /// JSON converter for a type `T`.
27 template <typename T>
28 struct JSONConverter {
29     static constexpr StorageType storage_type = StorageType::Text;
30 
31     /// Converts a value of type `T` to a `sqlite::Value`.
to_sqlite_valueexecutorchcoreml::sqlite::JSONConverter32     inline static sqlite::Value to_sqlite_value(const T& value) noexcept {
33         return value.to_json_string();
34     }
35 
36     /// Converts a `sqlite::UnOwnedValue` to a value of type `T`.
from_sqlite_valueexecutorchcoreml::sqlite::JSONConverter37     inline static T from_sqlite_value(const sqlite::UnOwnedValue& value) noexcept {
38         T result;
39         result.from_json_string(string_from_unowned_value(value));
40         return result;
41     }
42 };
43 
44 /// Type representing a JSON KeyValue store, the `Value` type uses a JSON converter.
45 ///
46 /// The `Value` type must implement `to_json(nlohmann::json& j, const T& value)` to convert
47 /// the value to json and `from_json(const nlohmann::json& j, T& value)` to convert the value from json.
48 /// The functions should be in the same namespace where the value is defined.
49 template<typename Key, typename Value, typename KeyConverter = Converter<Key>>
50 using JSONKeyValueStore = KeyValueStore<Key, Value, JSONConverter<Value>, KeyConverter>;
51 
52 } // namespace sqlite
53 } // namespace executorchcoreml
54