• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "base/ini_parser.h"
6 
7 #include "base/logging.h"
8 #include "base/strings/string_tokenizer.h"
9 
10 namespace base {
11 
INIParser()12 INIParser::INIParser() : used_(false) {}
13 
~INIParser()14 INIParser::~INIParser() {}
15 
Parse(const std::string & content)16 void INIParser::Parse(const std::string& content) {
17   DCHECK(!used_);
18   used_ = true;
19   base::StringTokenizer tokenizer(content, "\r\n");
20 
21   std::string current_section;
22   while (tokenizer.GetNext()) {
23     std::string line = tokenizer.token();
24     if (line.empty()) {
25       // Skips the empty line.
26       continue;
27     }
28     if (line[0] == '#' || line[0] == ';') {
29       // This line is a comment.
30       continue;
31     }
32     if (line[0] == '[') {
33       // It is a section header.
34       current_section = line.substr(1);
35       size_t end = current_section.rfind(']');
36       if (end != std::string::npos)
37         current_section.erase(end);
38     } else {
39       std::string key, value;
40       size_t equal = line.find('=');
41       if (equal != std::string::npos) {
42         key = line.substr(0, equal);
43         value = line.substr(equal + 1);
44         HandleTriplet(current_section, key, value);
45       }
46     }
47   }
48 }
49 
DictionaryValueINIParser()50 DictionaryValueINIParser::DictionaryValueINIParser() {}
51 
~DictionaryValueINIParser()52 DictionaryValueINIParser::~DictionaryValueINIParser() {}
53 
HandleTriplet(const std::string & section,const std::string & key,const std::string & value)54 void DictionaryValueINIParser::HandleTriplet(const std::string& section,
55                                              const std::string& key,
56                                              const std::string& value) {
57 
58   // Checks whether the section and key contain a '.' character.
59   // Those sections and keys break DictionaryValue's path format when not
60   // using the *WithoutPathExpansion methods.
61   if (section.find('.') == std::string::npos &&
62       key.find('.') == std::string::npos)
63     root_.SetString(section + "." + key, value);
64 }
65 
66 }  // namespace base
67