1// Copyright (c) 2010 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/string_split.h"
6
7#include "base/string_util.h"
8
9namespace base {
10
11bool SplitStringIntoKeyValues(
12    const std::string& line,
13    char key_value_delimiter,
14    std::string* key, std::vector<std::string>* values) {
15  key->clear();
16  values->clear();
17
18  // find the key string
19  size_t end_key_pos = line.find_first_of(key_value_delimiter);
20  if (end_key_pos == std::string::npos) {
21    DLOG(INFO) << "cannot parse key from line: " << line;
22    return false;    // no key
23  }
24  key->assign(line, 0, end_key_pos);
25
26  // find the values string
27  std::string remains(line, end_key_pos, line.size() - end_key_pos);
28  size_t begin_values_pos = remains.find_first_not_of(key_value_delimiter);
29  if (begin_values_pos == std::string::npos) {
30    DLOG(INFO) << "cannot parse value from line: " << line;
31    return false;   // no value
32  }
33  std::string values_string(remains, begin_values_pos,
34                            remains.size() - begin_values_pos);
35
36  // construct the values vector
37  values->push_back(values_string);
38  return true;
39}
40
41bool SplitStringIntoKeyValuePairs(
42    const std::string& line,
43    char key_value_delimiter,
44    char key_value_pair_delimiter,
45    std::vector<std::pair<std::string, std::string> >* kv_pairs) {
46  kv_pairs->clear();
47
48  std::vector<std::string> pairs;
49  SplitString(line, key_value_pair_delimiter, &pairs);
50
51  bool success = true;
52  for (size_t i = 0; i < pairs.size(); ++i) {
53    std::string key;
54    std::vector<std::string> value;
55    if (!SplitStringIntoKeyValues(pairs[i],
56                                  key_value_delimiter,
57                                  &key, &value)) {
58      // Don't return here, to allow for keys without associated
59      // values; just record that our split failed.
60      success = false;
61    }
62    DCHECK_LE(value.size(), 1U);
63    kv_pairs->push_back(make_pair(key, value.empty()? "" : value[0]));
64  }
65  return success;
66}
67
68}  // namespace base
69