2 * Copyright (C) 2016-2019 "IoT.bzh"
3 * Author José Bollo <jose.bollo@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * This simple program expands the object { "$ref": "#/path/to/a/target" }
25 * "b": { "$ref": "#/type/a" }
29 * will be exapanded to
38 * Invocation: program [file|-]...
40 * without arguments, it reads the input.
49 #include <json-c/json.h>
51 static size_t s2c(const char *str, const char *prefix, int width, int lprf, char *out)
57 #define P(x) do{ if (out) out[len] = (x); len++; pos++; }while(0)
58 /* translate the string */
61 /* get the char to convert */
64 /* set buf with next char */
70 /* remove ugly \/ put by json-c */
105 if (0 < c && c < ' ') {
107 buf[1] = (char)('0' + ((c >> 3) & 7));
108 buf[2] = (char)('0' + ((c >> 0) & 7));
117 /* add the char in the output */
119 for(i = 0 ; i < lprf ; i++)
123 for(i = 0 ; buf[i] ; i++)
125 if (pos >= width - 1) {
135 char *str2c(const char *str, const char *prefix, int width)
141 /* ensure defaults */
142 len = prefix ? strlen(prefix) : 0;
143 lprf = len > INT_MAX ? INT_MAX : (int)len;
144 width = width <= 0 || width - 2 <= lprf ? INT_MAX : width;
146 /* compute final size*/
147 len = s2c(str, prefix, width, lprf, NULL);
149 /* allocate the memory */
154 /* make the output */
155 s2c(str, prefix, width, lprf, out);
159 char *str2c_std(const char *str)
161 return str2c(str, "\t", 71);
164 char *str2c_inl(const char *str)
166 return str2c(str, 0, 0);
169 char *json2c(struct json_object *object, const char *prefix, int width)
171 return str2c(json_object_to_json_string_ext(object, 0), prefix, width);
174 char *json2c_std(struct json_object *object)
176 return str2c_std(json_object_to_json_string_ext(object, 0));
179 char *json2c_inl(struct json_object *object)
181 return str2c_inl(json_object_to_json_string_ext(object, 0));