1 // Copyright 2014 The Chromium OS 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 <brillo/strings/string_utils.h> 6 7 #include <algorithm> 8 #include <string.h> 9 #include <utility> 10 11 #include <base/strings/string_util.h> 12 #include <base/strings/stringprintf.h> 13 14 namespace brillo { 15 namespace string_utils { 16 17 std::vector<std::string> Split(const std::string& str, 18 const std::string& delimiter, 19 bool trim_whitespaces, 20 bool purge_empty_strings) { 21 std::vector<std::string> tokens; 22 if (str.empty()) 23 return tokens; 24 25 for (std::string::size_type i = 0;;) { 26 const std::string::size_type pos = 27 delimiter.empty() ? (i + 1) : str.find(delimiter, i); 28 std::string tmp_str{str.substr(i, pos - i)}; 29 if (trim_whitespaces) 30 base::TrimWhitespaceASCII(tmp_str, base::TRIM_ALL, &tmp_str); 31 if (!tmp_str.empty() || !purge_empty_strings) 32 tokens.emplace_back(std::move(tmp_str)); 33 if (pos >= str.size()) 34 break; 35 i = pos + delimiter.size(); 36 } 37 return tokens; 38 } 39 40 bool SplitAtFirst(const std::string& str, 41 const std::string& delimiter, 42 std::string* left_part, 43 std::string* right_part, 44 bool trim_whitespaces) { 45 bool delimiter_found = false; 46 std::string::size_type pos = str.find(delimiter); 47 if (pos != std::string::npos) { 48 *left_part = str.substr(0, pos); 49 *right_part = str.substr(pos + delimiter.size()); 50 delimiter_found = true; 51 } else { 52 *left_part = str; 53 right_part->clear(); 54 } 55 56 if (trim_whitespaces) { 57 base::TrimWhitespaceASCII(*left_part, base::TRIM_ALL, left_part); 58 base::TrimWhitespaceASCII(*right_part, base::TRIM_ALL, right_part); 59 } 60 61 return delimiter_found; 62 } 63 64 std::pair<std::string, std::string> SplitAtFirst(const std::string& str, 65 const std::string& delimiter, 66 bool trim_whitespaces) { 67 std::pair<std::string, std::string> pair; 68 SplitAtFirst(str, delimiter, &pair.first, &pair.second, trim_whitespaces); 69 return pair; 70 } 71 72 std::string ToString(double value) { 73 return base::StringPrintf("%g", value); 74 } 75 76 std::string ToString(bool value) { 77 return value ? "true" : "false"; 78 } 79 80 std::string GetBytesAsString(const std::vector<uint8_t>& buffer) { 81 return std::string(buffer.begin(), buffer.end()); 82 } 83 84 std::vector<uint8_t> GetStringAsBytes(const std::string& str) { 85 return std::vector<uint8_t>(str.begin(), str.end()); 86 } 87 88 } // namespace string_utils 89 } // namespace brillo 90