blob: 282a692ae45f0e2a51e16fddabd4bbb069b8a997 [file] [log] [blame]
Nigel Tao0eee2312020-07-03 12:48:37 +10001// Copyright 2020 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// ----------------
16
17// process-json-numbers.c processes all the numbers in the JSON-formatted data
18// read from stdin. It succeeds (with exit code 0) if the input is valid JSON
19// and all of the numbers within were processed without error.
20//
21// Without further flags, processing is a no-op and the program only verifies
22// the JSON structure.
23//
24// Pass -e (--emit-number-str) to emit each number (as a string) on its own
25// line.
26//
27// Pass -p (--parse-number-f64) to call wuffs_base__parse_number_f64 on each
28// number. Timing this program with and without this flag gives a rough measure
29// of how much time is spent solely in wuffs_base__parse_number_f64.
30//
31// Pass -r (--render-number-f64) to call wuffs_base__render_number_f64 (with
32// WUFFS_BASE__RENDER_NUMBER_FXX__JUST_ENOUGH_PRECISION) on each number. Timing
33// this program with and without this flag gives a rough measure of how much
34// time is spent solely in wuffs_base__render_number_f64.
35//
36// The -r flag is ignored unless -p is also passed.
37//
38// This program's purpose is to benchmark the wuffs_base__etc_f64 functions.
39// It's not about JSON per se, but JSON files are a source of realistic
40// floating point numbers.
41
42#include <inttypes.h>
43#include <stdio.h>
44#include <string.h>
45#include <unistd.h>
46
47// Wuffs ships as a "single file C library" or "header file library" as per
48// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
49//
50// To use that single file as a "foo.c"-like implementation, instead of a
51// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
52// compiling it.
53#define WUFFS_IMPLEMENTATION
54
Nigel Tao6fb76972021-10-07 14:36:35 +110055// Defining the WUFFS_CONFIG__STATIC_FUNCTIONS macro is optional, but when
56// combined with WUFFS_IMPLEMENTATION, it demonstrates making all of Wuffs'
57// functions have static storage.
58//
59// This can help the compiler ignore or discard unused code, which can produce
60// faster compiles and smaller binaries. Other motivations are discussed in the
61// "ALLOW STATIC IMPLEMENTATION" section of
62// https://raw.githubusercontent.com/nothings/stb/master/docs/stb_howto.txt
63#define WUFFS_CONFIG__STATIC_FUNCTIONS
64
Nigel Tao0eee2312020-07-03 12:48:37 +100065// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
Nigel Tao2f788042021-01-23 19:29:19 +110066// release/c/etc.c choose which parts of Wuffs to build. That file contains the
67// entire Wuffs standard library, implementing a variety of codecs and file
Nigel Tao0eee2312020-07-03 12:48:37 +100068// formats. Without this macro definition, an optimizing compiler or linker may
69// very well discard Wuffs code for unused codecs, but listing the Wuffs
70// modules we use makes that process explicit. Preprocessing means that such
71// code simply isn't compiled.
72#define WUFFS_CONFIG__MODULES
73#define WUFFS_CONFIG__MODULE__BASE
74#define WUFFS_CONFIG__MODULE__JSON
75
76// If building this program in an environment that doesn't easily accommodate
77// relative includes, you can use the script/inline-c-relative-includes.go
Nigel Taoa20a2bb2020-09-07 21:06:58 +100078// program to generate a stand-alone C file.
Nigel Tao0eee2312020-07-03 12:48:37 +100079#include "../release/c/wuffs-unsupported-snapshot.c"
80
Nigel Tao27766ae2020-07-09 10:59:54 +100081// Uncomment this to use the github.com/lemire/fast_double_parser library. This
82// header-only library is C++, not C.
Nigel Tao510c2302020-09-07 22:59:45 +100083// #define USE_LEMIRE_FAST_DOUBLE_PARSER
Nigel Tao27766ae2020-07-09 10:59:54 +100084
Nigel Tao510c2302020-09-07 22:59:45 +100085#ifdef USE_LEMIRE_FAST_DOUBLE_PARSER
Nigel Tao27766ae2020-07-09 10:59:54 +100086#include "/the/path/to/fast_double_parser/include/fast_double_parser.h"
87#endif
88
Nigel Tao0eee2312020-07-03 12:48:37 +100089// Wuffs allows either statically or dynamically allocated work buffers. This
90// program exercises static allocation.
91#define WORK_BUFFER_ARRAY_SIZE \
92 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
93#if WORK_BUFFER_ARRAY_SIZE > 0
94uint8_t g_work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
95#else
96// Not all C/C++ compilers support 0-length arrays.
97uint8_t g_work_buffer_array[1];
98#endif
99
100#ifndef SRC_BUFFER_ARRAY_SIZE
101#define SRC_BUFFER_ARRAY_SIZE (64 * 1024 * 1024)
102#endif
103#ifndef TOKEN_BUFFER_ARRAY_SIZE
104#define TOKEN_BUFFER_ARRAY_SIZE (128 * 1024)
105#endif
106
107uint8_t g_src_buffer_array[SRC_BUFFER_ARRAY_SIZE];
108wuffs_base__token g_tok_buffer_array[TOKEN_BUFFER_ARRAY_SIZE];
109
110wuffs_base__io_buffer g_src;
111wuffs_base__token_buffer g_tok;
112
113wuffs_json__decoder g_dec;
114
115#define TRY(error_msg) \
116 do { \
117 const char* z = error_msg; \
118 if (z) { \
119 return z; \
120 } \
121 } while (false)
122
123// ignore_return_value suppresses errors from -Wall -Werror.
124static void //
125ignore_return_value(int ignored) {}
126
127const char* //
128read_src() {
129 if (g_src.meta.closed) {
130 return "main: internal error: read requested on a closed source";
131 }
132 wuffs_base__io_buffer__compact(&g_src);
133 if (g_src.meta.wi >= g_src.data.len) {
134 return "main: g_src buffer is full";
135 }
136 size_t n = fread(g_src.data.ptr + g_src.meta.wi, sizeof(uint8_t),
137 g_src.data.len - g_src.meta.wi, stdin);
138 g_src.meta.wi += n;
139 g_src.meta.closed = feof(stdin);
140 if ((n == 0) && !g_src.meta.closed) {
141 return "main: read error";
142 }
143 return NULL;
144}
145
146// ----
147
148struct {
149 int remaining_argc;
150 char** remaining_argv;
151
152 bool emit_number_str;
153 bool parse_number_f64;
154 bool render_number_f64;
155} g_flags = {0};
156
157const char* //
158parse_flags(int argc, char** argv) {
159 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
160 for (; c < argc; c++) {
161 char* arg = argv[c];
162 if (*arg++ != '-') {
163 break;
164 }
165
166 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
167 // cases, a bare "-" is not a flag (some programs may interpret it as
168 // stdin) and a bare "--" means to stop parsing flags.
169 if (*arg == '\x00') {
170 break;
171 } else if (*arg == '-') {
172 arg++;
173 if (*arg == '\x00') {
174 c++;
175 break;
176 }
177 }
178
179 if (!strcmp(arg, "e") || !strcmp(arg, "emit-number-str")) {
180 g_flags.emit_number_str = true;
181 continue;
182 }
183 if (!strcmp(arg, "p") || !strcmp(arg, "parse-number-f64")) {
184 g_flags.parse_number_f64 = true;
185 continue;
186 }
187 if (!strcmp(arg, "r") || !strcmp(arg, "render-number-f64")) {
188 g_flags.render_number_f64 = true;
189 continue;
190 }
191
192 return "main: unrecognized flag argument";
193 }
194
195 g_flags.remaining_argc = argc - c;
196 g_flags.remaining_argv = argv + c;
197 return NULL;
198}
199
200const char* //
201main1(int argc, char** argv) {
202 TRY(parse_flags(argc, argv));
203 if (g_flags.remaining_argc > 0) {
204 return "main: bad argument: use \"program < input\", not \"program input\"";
205 }
206
207 uint8_t new_line[1];
208 new_line[0] = '\n';
209
210 g_src = wuffs_base__make_io_buffer(
211 wuffs_base__make_slice_u8(g_src_buffer_array, SRC_BUFFER_ARRAY_SIZE),
212 wuffs_base__empty_io_buffer_meta());
213
214 g_tok = wuffs_base__make_token_buffer(
215 wuffs_base__make_slice_token(g_tok_buffer_array, TOKEN_BUFFER_ARRAY_SIZE),
216 wuffs_base__empty_token_buffer_meta());
217
218 wuffs_base__status init_status = wuffs_json__decoder__initialize(
219 &g_dec, sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
220 if (!wuffs_base__status__is_ok(&init_status)) {
221 return wuffs_base__status__message(&init_status);
222 }
223
224 uint64_t pos = 0;
225 while (true) {
226 wuffs_base__status status = wuffs_json__decoder__decode_tokens(
227 &g_dec, &g_tok, &g_src,
228 wuffs_base__make_slice_u8(g_work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
229
230 while (g_tok.meta.ri < g_tok.meta.wi) {
231 wuffs_base__token* t = &g_tok.data.ptr[g_tok.meta.ri++];
232 uint64_t len = wuffs_base__token__length(t);
233
234 if (wuffs_base__token__value_base_category(t) ==
235 WUFFS_BASE__TOKEN__VBC__NUMBER) {
236 uint64_t buf_pos = pos - g_src.meta.pos;
237 uint64_t buf_len = g_src.data.len;
238 if ((buf_len < buf_pos) || ((buf_len - buf_pos) < len)) {
239 return "main: internal error: inconsistent token position/length";
240 }
241
242 if (g_flags.emit_number_str) {
243 const int stdout_fd = 1;
244 ignore_return_value(write(stdout_fd, &g_src.data.ptr[buf_pos], len));
245 ignore_return_value(write(stdout_fd, &new_line[0], 1));
246 }
247
248 if (g_flags.parse_number_f64) {
Nigel Tao27766ae2020-07-09 10:59:54 +1000249 wuffs_base__result_f64 r;
250
Nigel Tao510c2302020-09-07 22:59:45 +1000251#ifdef USE_LEMIRE_FAST_DOUBLE_PARSER
Nigel Tao27766ae2020-07-09 10:59:54 +1000252 // Wuffs (and its JSON parser) works with slices (pointer-length
253 // pairs) but fast_double_parser works with NUL-terminated strings.
254 char buf[1024];
255 if (len > 1023) {
256 return "main: number-as-string is too long";
257 }
258 memcpy(&buf[0], &g_src.data.ptr[buf_pos], len);
259 buf[len] = 0;
260 if (!fast_double_parser::decimal_separator_dot::parse_number(
261 &buf[0], &r.value)) {
262 return "main: could not parse number";
263 }
264 r.status = wuffs_base__make_status(NULL);
265#else
266 r = wuffs_base__parse_number_f64(
Nigel Tao6b7ce302020-07-07 16:19:46 +1000267 wuffs_base__make_slice_u8(&g_src.data.ptr[buf_pos], len),
268 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao0eee2312020-07-03 12:48:37 +1000269 if (!wuffs_base__status__is_ok(&r.status)) {
270 return wuffs_base__status__message(&r.status);
271 }
Nigel Tao27766ae2020-07-09 10:59:54 +1000272#endif
Nigel Tao0eee2312020-07-03 12:48:37 +1000273
274 if (g_flags.render_number_f64) {
275 uint8_t render_buffer[2048];
276 size_t n = wuffs_base__render_number_f64(
277 wuffs_base__make_slice_u8(&render_buffer[0], 2048), r.value, 0,
278 WUFFS_BASE__RENDER_NUMBER_FXX__JUST_ENOUGH_PRECISION);
279 if (n == 0) {
280 return "main: internal error: couldn't render_number_f64";
281 }
282 }
283 }
284 }
285
286 pos += len;
287 if (0 > ((int64_t)pos)) {
288 return "main: input is too long";
289 }
290 }
291
292 if (status.repr == NULL) {
293 return NULL;
294 } else if (status.repr == wuffs_base__suspension__short_read) {
295 TRY(read_src());
296 } else if (status.repr == wuffs_base__suspension__short_write) {
297 wuffs_base__token_buffer__compact(&g_tok);
298 } else {
299 return wuffs_base__status__message(&status);
300 }
301 }
302}
303
304// ----
305
306int //
307compute_exit_code(const char* status_msg) {
308 if (!status_msg) {
309 return 0;
310 }
311 size_t n = strnlen(status_msg, 2047);
312 if (n >= 2047) {
313 status_msg = "main: internal error: error message is too long";
314 n = strnlen(status_msg, 2047);
315 }
316 fprintf(stderr, "%s\n", status_msg);
Nigel Taoa51867d2021-05-19 21:34:09 +1000317 // Return an exit code of 1 for regular (foreseen) errors, e.g. badly
Nigel Tao0eee2312020-07-03 12:48:37 +1000318 // formatted or unsupported input.
319 //
320 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
321 // run-time checks found that an internal invariant did not hold.
322 //
323 // Automated testing, including badly formatted inputs, can therefore
324 // discriminate between expected failure (exit code 1) and unexpected failure
325 // (other non-zero exit codes). Specifically, exit code 2 for internal
326 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
327 // linux) for a segmentation fault (e.g. null pointer dereference).
328 return strstr(status_msg, "internal error:") ? 2 : 1;
329}
330
331int //
332main(int argc, char** argv) {
333 const char* z = main1(argc, argv);
334 int exit_code = compute_exit_code(z);
335 return exit_code;
336}