1 /******************************************************************************
2  *
3  *  Copyright (C) 2015 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 #define LOG_TAG "hash_map_utils"
19 
20 #include "osi/include/hash_map_utils.h"
21 
22 #include <base/logging.h>
23 #include <string.h>
24 
25 #include "osi/include/allocator.h"
26 #include "osi/include/log.h"
27 #include "osi/include/osi.h"
28 
29 std::unordered_map<std::string, std::string>
hash_map_utils_new_from_string_params(const char * params)30 hash_map_utils_new_from_string_params(const char* params) {
31   CHECK(params != NULL);
32 
33   std::unordered_map<std::string, std::string> map;
34 
35   char* str = osi_strdup(params);
36   if (!str) return map;
37 
38   LOG_VERBOSE(LOG_TAG, "%s: source string: '%s'", __func__, str);
39 
40   // Parse |str| and add extracted key-and-value pair(s) in |map|.
41   int items = 0;
42   char* tmpstr;
43   char* kvpair = strtok_r(str, ";", &tmpstr);
44   while (kvpair && *kvpair) {
45     char* eq = strchr(kvpair, '=');
46 
47     if (eq == kvpair) goto next_pair;
48 
49     char* key;
50     char* value;
51     if (eq) {
52       key = osi_strndup(kvpair, eq - kvpair);
53 
54       // The increment of |eq| moves |eq| to the beginning of the value.
55       ++eq;
56       value = (*eq != '\0') ? osi_strdup(eq) : osi_strdup("");
57     } else {
58       key = osi_strdup(kvpair);
59       value = osi_strdup("");
60     }
61 
62     map[key] = value;
63 
64     osi_free(key);
65     osi_free(value);
66 
67     items++;
68   next_pair:
69     kvpair = strtok_r(NULL, ";", &tmpstr);
70   }
71 
72   if (!items) LOG_VERBOSE(LOG_TAG, "%s: no items found in string\n", __func__);
73 
74   osi_free(str);
75   return map;
76 }
77 
hash_map_utils_dump_string_keys_string_values(std::unordered_map<std::string,std::string> & map)78 void hash_map_utils_dump_string_keys_string_values(
79     std::unordered_map<std::string, std::string>& map) {
80   for (const auto& ptr : map) {
81     LOG_INFO(LOG_TAG, "key: '%s' value: '%s'\n", ptr.first.c_str(),
82              ptr.second.c_str());
83   }
84 }
85