ini_parser.cc 2.0 KB

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