• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
30 std::unordered_map<std::string, std::string>
hash_map_utils_new_from_string_params(const char * params)31 hash_map_utils_new_from_string_params(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) return map;
38 
39   // Parse |str| and add extracted key-and-value pair(s) in |map|.
40   char* tmpstr;
41   char* kvpair = strtok_r(str, ";", &tmpstr);
42   while (kvpair && *kvpair) {
43     char* eq = strchr(kvpair, '=');
44 
45     if (eq == kvpair) goto next_pair;
46 
47     char* key;
48     char* value;
49     if (eq) {
50       key = osi_strndup(kvpair, eq - kvpair);
51 
52       // The increment of |eq| moves |eq| to the beginning of the value.
53       ++eq;
54       value = (*eq != '\0') ? osi_strdup(eq) : osi_strdup("");
55     } else {
56       key = osi_strdup(kvpair);
57       value = osi_strdup("");
58     }
59 
60     map[key] = value;
61 
62     osi_free(key);
63     osi_free(value);
64   next_pair:
65     kvpair = strtok_r(NULL, ";", &tmpstr);
66   }
67 
68   osi_free(str);
69   return map;
70 }
71