1 // Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "common/app_db.h"
7 #include <app_preference.h>
10 #include "common/string_utils.h"
15 const char* kSectionPrefix = "_SECT_";
16 const char* kSectionSuffix = "_SECT_";
20 class PreferenceAppDB : public AppDB {
23 virtual bool HasKey(const std::string& section,
24 const std::string& key) const;
25 virtual std::string Get(const std::string& section,
26 const std::string& key) const;
27 virtual void Set(const std::string& section,
28 const std::string& key,
29 const std::string& value);
30 virtual void GetKeys(const std::string& section,
31 std::list<std::string>* keys) const;
32 virtual void Remove(const std::string& section,
33 const std::string& key);
36 PreferenceAppDB::PreferenceAppDB() {
39 bool PreferenceAppDB::HasKey(const std::string& section,
40 const std::string& key) const {
42 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
43 return preference_is_existing(combined_key.c_str(), &existed) == 0 && existed;
46 std::string PreferenceAppDB::Get(const std::string& section,
47 const std::string& key) const {
48 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
50 if (preference_get_string(combined_key.c_str(), &value) == 0) {
51 std::unique_ptr<char, decltype(std::free)*> ptr {value, std::free};
52 return std::string(value);
57 void PreferenceAppDB::Set(const std::string& section,
58 const std::string& key,
59 const std::string& value) {
60 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
61 preference_set_string(combined_key.c_str(), value.c_str());
64 void PreferenceAppDB::GetKeys(const std::string& section,
65 std::list<std::string>* keys) const {
66 auto callback = [](const char* key, void *user_data) {
67 auto list = static_cast<std::list<std::string>*>(user_data);
68 if (utils::StartsWith(key, list->front())) {
69 list->push_back(key+list->front().size());
73 std::string key_prefix = kSectionPrefix + section + kSectionSuffix;
74 keys->push_front(key_prefix);
75 preference_foreach_item(callback, keys);
79 void PreferenceAppDB::Remove(const std::string& section,
80 const std::string& key) {
81 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
82 preference_remove(combined_key.c_str());
86 AppDB* AppDB::GetInstance() {
87 static PreferenceAppDB instance;