OSDN Git Service

d0f6da1a6cce83b863bf8279284908bf55156962
[android-x86/system-extras.git] / ext4_utils / unencrypted_properties.h
1 #include <string>
2 #include <fstream>
3
4 // key names for properties we use
5 namespace properties {
6     extern const char* key;
7     extern const char* ref;
8     extern const char* is_default;
9 }
10
11 /**
12  * Class to store data on the unencrypted folder of a device.
13  * Note that the folder must exist before this class is constructed.
14  * All names must be valid single level (no '/') file or directory names
15  * Data is organized hierarchically so we can get a child folder
16  */
17 class UnencryptedProperties
18 {
19 public:
20     // Get path of folder. Must create before using any properties
21     // This is to allow proper setting of SELinux policy
22     static std::string GetPath(const char* device);
23
24     // Opens properties folder on named device.
25     // If folder does not exist, OK will return false, all
26     // getters will return default properties and setters will fail.
27     UnencryptedProperties(const char* device);
28
29     // Get named object. Return default if object does not exist or error.
30     template<typename t> t Get(const char* name, t default_value = t()) const;
31
32     // Set named object. Return true if success, false otherwise
33     template<typename t> bool Set(const char* name, t const& value);
34
35     // Get child properties
36     UnencryptedProperties GetChild(const char* name) const;
37
38     // Remove named object
39     bool Remove(const char* name);
40
41     // Does folder exist?
42     bool OK() const;
43
44 private:
45     UnencryptedProperties();
46     std::string folder_;
47 };
48
49
50 template<typename t> t UnencryptedProperties::Get(const char* name,
51                                                   t default_value) const
52 {
53     if (!OK()) return default_value;
54     t value = default_value;
55     std::ifstream(folder_ + "/" + name) >> value;
56     return value;
57 }
58
59 template<typename t> bool UnencryptedProperties::Set(const char* name,
60                                                      t const& value)
61 {
62     if (!OK()) return false;
63     std::ofstream o(folder_ + "/" + name);
64     o << value;
65     return !o.fail();
66 }
67
68 // Specialized getters/setters for strings
69 template<> std::string UnencryptedProperties::Get(const char* name,
70                                       std::string default_value) const;
71
72 template<> bool UnencryptedProperties::Set(const char* name,
73                                            std::string const& value);