1 /* 2 * 3 * Copyright 2015 gRPC authors. 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 <grpc/support/port_platform.h> 20 21 #include <inttypes.h> 22 #include <string.h> 23 24 #include <grpc/support/alloc.h> 25 #include <grpc/support/log.h> 26 #include <grpc/support/string_util.h> 27 28 #include "src/core/lib/json/json.h" 29 30 grpc_json* grpc_json_create(grpc_json_type type) { 31 grpc_json* json = static_cast<grpc_json*>(gpr_zalloc(sizeof(*json))); 32 json->type = type; 33 34 return json; 35 } 36 37 void grpc_json_destroy(grpc_json* json) { 38 while (json->child) { 39 grpc_json_destroy(json->child); 40 } 41 42 if (json->next) { 43 json->next->prev = json->prev; 44 } 45 46 if (json->prev) { 47 json->prev->next = json->next; 48 } else if (json->parent) { 49 json->parent->child = json->next; 50 } 51 52 if (json->owns_value) { 53 gpr_free((void*)json->value); 54 } 55 56 gpr_free(json); 57 } 58 59 grpc_json* grpc_json_link_child(grpc_json* parent, grpc_json* child, 60 grpc_json* sibling) { 61 // link child up to parent 62 child->parent = parent; 63 // first child case. 64 if (parent->child == nullptr) { 65 GPR_ASSERT(sibling == nullptr); 66 parent->child = child; 67 return child; 68 } 69 if (sibling == nullptr) { 70 sibling = parent->child; 71 } 72 // always find the right most sibling. 73 while (sibling->next != nullptr) { 74 sibling = sibling->next; 75 } 76 sibling->next = child; 77 return child; 78 } 79 80 grpc_json* grpc_json_create_child(grpc_json* sibling, grpc_json* parent, 81 const char* key, const char* value, 82 grpc_json_type type, bool owns_value) { 83 grpc_json* child = grpc_json_create(type); 84 grpc_json_link_child(parent, child, sibling); 85 child->owns_value = owns_value; 86 child->value = value; 87 child->key = key; 88 return child; 89 } 90 91 grpc_json* grpc_json_add_number_string_child(grpc_json* parent, grpc_json* it, 92 const char* name, int64_t num) { 93 char* num_str; 94 gpr_asprintf(&num_str, "%" PRId64, num); 95 return grpc_json_create_child(it, parent, name, num_str, GRPC_JSON_STRING, 96 true); 97 } 98