| 196 | } |
| 197 | |
| 198 | CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target) |
| 199 | { |
| 200 | size_t child_index = 0; |
| 201 | cJSON *current_child = 0; |
| 202 | |
| 203 | if ((object == NULL) || (target == NULL)) |
| 204 | { |
| 205 | return NULL; |
| 206 | } |
| 207 | |
| 208 | if (object == target) |
| 209 | { |
| 210 | /* found */ |
| 211 | return (char*)cJSONUtils_strdup((const unsigned char*)""); |
| 212 | } |
| 213 | |
| 214 | /* recursively search all children of the object or array */ |
| 215 | for (current_child = object->child; current_child != NULL; (void)(current_child = current_child->next), child_index++) |
| 216 | { |
| 217 | unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target); |
| 218 | /* found the target? */ |
| 219 | if (target_pointer != NULL) |
| 220 | { |
| 221 | if (cJSON_IsArray(object)) |
| 222 | { |
| 223 | /* reserve enough memory for a 64 bit integer + '/' and '\0' */ |
| 224 | unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/")); |
| 225 | /* check if conversion to unsigned long is valid |
| 226 | * This should be eliminated at compile time by dead code elimination |
| 227 | * if size_t is an alias of unsigned long, or if it is bigger */ |
| 228 | if (child_index > ULONG_MAX) |
| 229 | { |
| 230 | cJSON_free(target_pointer); |
| 231 | cJSON_free(full_pointer); |
| 232 | return NULL; |
| 233 | } |
| 234 | sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* /<array_index><path> */ |
| 235 | cJSON_free(target_pointer); |
| 236 | |
| 237 | return (char*)full_pointer; |
| 238 | } |
| 239 | |
| 240 | if (cJSON_IsObject(object)) |
| 241 | { |
| 242 | unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + pointer_encoded_length((unsigned char*)current_child->string) + 2); |
| 243 | full_pointer[0] = '/'; |
| 244 | encode_string_as_pointer(full_pointer + 1, (unsigned char*)current_child->string); |
| 245 | strcat((char*)full_pointer, (char*)target_pointer); |
| 246 | cJSON_free(target_pointer); |
| 247 | |
| 248 | return (char*)full_pointer; |
| 249 | } |
| 250 | |
| 251 | /* reached leaf of the tree, found nothing */ |
| 252 | cJSON_free(target_pointer); |
| 253 | return NULL; |
| 254 | } |
| 255 | } |
searching dependent graphs…