2 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "common/string_utils.h"
19 #include <uuid/uuid.h>
34 std::string GenerateUUID() {
38 uuid_unparse(uuid, tmp);
39 return std::string(tmp);
42 bool StartsWith(const std::string& str, const std::string& sub) {
43 if (sub.size() > str.size()) return false;
44 return std::equal(sub.begin(), sub.end(), str.begin());
47 bool EndsWith(const std::string& str, const std::string& sub) {
48 if (sub.size() > str.size()) return false;
49 return std::equal(sub.rbegin(), sub.rend(), str.rbegin());
52 std::string ReplaceAll(const std::string& replace,
53 const std::string& from, const std::string& to) {
54 std::string str = replace;
55 size_t pos = str.find(from);
56 while (pos != std::string::npos) {
57 str.replace(pos, from.length(), to);
58 pos = str.find(from, pos+to.length());
63 std::string GetCurrentMilliSeconds() {
64 std::ostringstream ss;
66 clock_gettime(CLOCK_REALTIME, &spec);
67 ss << (spec.tv_sec%10000) << "." <<
68 std::setw(3) << std::setfill('0') << (round(spec.tv_nsec / 1.0e6));
72 bool SplitString(const std::string &str,
73 std::string *part_1, std::string *part_2, const char delim) {
74 if (part_1 == nullptr || part_2 == nullptr)
77 size_t pos = str.find(delim);
78 if (pos == std::string::npos)
81 *part_1 = str.substr(0, pos);
82 *part_2 = str.substr(pos+1);
86 std::string UrlDecode(const std::string& url) {
87 std::unique_ptr<char, decltype(std::free)*> decoded_str {
88 g_uri_unescape_string(url.c_str(), NULL), std::free };
89 return decoded_str.get() != nullptr ? std::string(decoded_str.get()) : url;
92 std::string UrlEncode(const std::string& url) {
93 std::unique_ptr<char, decltype(std::free)*> encoded_str {
94 g_uri_escape_string(url.c_str(), NULL, TRUE), std::free };
95 return encoded_str.get() != nullptr ? std::string(encoded_str.get()) : url;
98 std::string Base64Encode(const unsigned char* data, size_t len) {
99 gchar* encoded = g_base64_encode(data, len);
100 std::unique_ptr<gchar, decltype(g_free)*> encoded_ptr {encoded, g_free};
101 return std::string(encoded);
105 } // namespace common