1 /******************************************************************************
2  *
3  *  Copyright 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 
19 #include "osi/include/hash_map_utils.h"
20 
21 #include <bluetooth/log.h>
22 
23 #include <cstring>
24 #include <map>
25 #include <string>
26 
27 #include "osi/include/allocator.h"
28 #include "osi/include/osi.h"
29 
hash_map_utils_new_from_string_params(const char * params)30 std::unordered_map<std::string, std::string> hash_map_utils_new_from_string_params(
31         const char* params) {
32   bluetooth::log::assert_that(params != NULL, "assert failed: params != NULL");
33 
34   std::unordered_map<std::string, std::string> map;
35 
36   char* str = osi_strdup(params);
37   if (!str) {
38     return map;
39   }
40 
41   // Parse |str| and add extracted key-and-value pair(s) in |map|.
42   char* tmpstr;
43   char* kvpair = strtok_r(str, ";", &tmpstr);
44   while (kvpair && *kvpair) {
45     char* eq = strchr(kvpair, '=');
46 
47     if (eq == kvpair) {
48       goto next_pair;
49     }
50 
51     char* key;
52     char* value;
53     if (eq) {
54       key = osi_strndup(kvpair, eq - kvpair);
55 
56       // The increment of |eq| moves |eq| to the beginning of the value.
57       ++eq;
58       value = (*eq != '\0') ? osi_strdup(eq) : osi_strdup("");
59     } else {
60       key = osi_strdup(kvpair);
61       value = osi_strdup("");
62     }
63 
64     map[key] = value;
65 
66     osi_free(key);
67     osi_free(value);
68   next_pair:
69     kvpair = strtok_r(NULL, ";", &tmpstr);
70   }
71 
72   osi_free(str);
73   return map;
74 }
75