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