tommycli@chromium.org | 7d9385e | 2013-06-19 08:31:12 +0900 | [diff] [blame] | 1 | // Copyright 2013 The Chromium Authors. 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. |
| 4 | |
| 5 | #ifndef BASE_INI_PARSER_H_ |
| 6 | #define BASE_INI_PARSER_H_ |
| 7 | |
| 8 | #include <string> |
| 9 | |
| 10 | #include "base/base_export.h" |
| 11 | #include "base/basictypes.h" |
| 12 | #include "base/values.h" |
| 13 | |
| 14 | namespace base { |
| 15 | |
| 16 | // Parses INI files in a string. Users should in inherit from this class. |
| 17 | // This is a very basic INI parser with these characteristics: |
| 18 | // - Ignores blank lines. |
| 19 | // - Ignores comment lines beginning with '#' or ';'. |
| 20 | // - Duplicate key names in the same section will simply cause repeated calls |
| 21 | // to HandleTriplet with the same |section| and |key| parameters. |
| 22 | // - No escape characters supported. |
| 23 | // - Global properties result in calls to HandleTriplet with an empty string in |
| 24 | // the |section| argument. |
| 25 | // - Section headers begin with a '[' character. It is recommended, but |
| 26 | // not required to close the header bracket with a ']' character. All |
| 27 | // characters after a closing ']' character is ignored. |
| 28 | // - Key value pairs are indicated with an '=' character. Whitespace is not |
| 29 | // ignored. Quoting is not supported. Everything before the first '=' |
| 30 | // is considered the |key|, and everything after is the |value|. |
| 31 | class BASE_EXPORT INIParser { |
| 32 | public: |
| 33 | INIParser(); |
| 34 | virtual ~INIParser(); |
| 35 | |
| 36 | // May only be called once per instance. |
| 37 | void Parse(const std::string& content); |
| 38 | |
| 39 | private: |
| 40 | virtual void HandleTriplet(const std::string& section, |
| 41 | const std::string& key, |
| 42 | const std::string& value) = 0; |
| 43 | |
| 44 | bool used_; |
| 45 | }; |
| 46 | |
| 47 | // Parsed values are stored as strings at the "section.key" path. Triplets with |
| 48 | // |section| or |key| parameters containing '.' are ignored. |
| 49 | class BASE_EXPORT DictionaryValueINIParser : public INIParser { |
| 50 | public: |
| 51 | DictionaryValueINIParser(); |
| 52 | virtual ~DictionaryValueINIParser(); |
| 53 | |
| 54 | const DictionaryValue& root() const { return root_; } |
| 55 | |
| 56 | private: |
| 57 | // INIParser implementation. |
| 58 | virtual void HandleTriplet(const std::string& section, |
| 59 | const std::string& key, |
| 60 | const std::string& value) OVERRIDE; |
| 61 | |
| 62 | DictionaryValue root_; |
| 63 | |
| 64 | DISALLOW_COPY_AND_ASSIGN(DictionaryValueINIParser); |
| 65 | }; |
| 66 | |
| 67 | } // namespace base |
| 68 | |
| 69 | #endif // BASE_INI_PARSER_H_ |