blob: e4636681fe724cb742555821320af38c26b65bf8 [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
55// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
56// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
57// the entire Wuffs standard library, implementing a variety of codecs and file
58// formats. Without this macro definition, an optimizing compiler or linker may
59// very well discard Wuffs code for unused codecs, but listing the Wuffs
60// modules we use makes that process explicit. Preprocessing means that such
61// code simply isn't compiled.
62#define WUFFS_CONFIG__MODULES
63#define WUFFS_CONFIG__MODULE__BASE
64#define WUFFS_CONFIG__MODULE__JSON
65
66// If building this program in an environment that doesn't easily accommodate
67// relative includes, you can use the script/inline-c-relative-includes.go
68// program to generate a stand-alone C++ file.
69#include "../release/c/wuffs-unsupported-snapshot.c"
70
71// Wuffs allows either statically or dynamically allocated work buffers. This
72// program exercises static allocation.
73#define WORK_BUFFER_ARRAY_SIZE \
74 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
75#if WORK_BUFFER_ARRAY_SIZE > 0
76uint8_t g_work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
77#else
78// Not all C/C++ compilers support 0-length arrays.
79uint8_t g_work_buffer_array[1];
80#endif
81
82#ifndef SRC_BUFFER_ARRAY_SIZE
83#define SRC_BUFFER_ARRAY_SIZE (64 * 1024 * 1024)
84#endif
85#ifndef TOKEN_BUFFER_ARRAY_SIZE
86#define TOKEN_BUFFER_ARRAY_SIZE (128 * 1024)
87#endif
88
89uint8_t g_src_buffer_array[SRC_BUFFER_ARRAY_SIZE];
90wuffs_base__token g_tok_buffer_array[TOKEN_BUFFER_ARRAY_SIZE];
91
92wuffs_base__io_buffer g_src;
93wuffs_base__token_buffer g_tok;
94
95wuffs_json__decoder g_dec;
96
97#define TRY(error_msg) \
98 do { \
99 const char* z = error_msg; \
100 if (z) { \
101 return z; \
102 } \
103 } while (false)
104
105// ignore_return_value suppresses errors from -Wall -Werror.
106static void //
107ignore_return_value(int ignored) {}
108
109const char* //
110read_src() {
111 if (g_src.meta.closed) {
112 return "main: internal error: read requested on a closed source";
113 }
114 wuffs_base__io_buffer__compact(&g_src);
115 if (g_src.meta.wi >= g_src.data.len) {
116 return "main: g_src buffer is full";
117 }
118 size_t n = fread(g_src.data.ptr + g_src.meta.wi, sizeof(uint8_t),
119 g_src.data.len - g_src.meta.wi, stdin);
120 g_src.meta.wi += n;
121 g_src.meta.closed = feof(stdin);
122 if ((n == 0) && !g_src.meta.closed) {
123 return "main: read error";
124 }
125 return NULL;
126}
127
128// ----
129
130struct {
131 int remaining_argc;
132 char** remaining_argv;
133
134 bool emit_number_str;
135 bool parse_number_f64;
136 bool render_number_f64;
137} g_flags = {0};
138
139const char* //
140parse_flags(int argc, char** argv) {
141 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
142 for (; c < argc; c++) {
143 char* arg = argv[c];
144 if (*arg++ != '-') {
145 break;
146 }
147
148 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
149 // cases, a bare "-" is not a flag (some programs may interpret it as
150 // stdin) and a bare "--" means to stop parsing flags.
151 if (*arg == '\x00') {
152 break;
153 } else if (*arg == '-') {
154 arg++;
155 if (*arg == '\x00') {
156 c++;
157 break;
158 }
159 }
160
161 if (!strcmp(arg, "e") || !strcmp(arg, "emit-number-str")) {
162 g_flags.emit_number_str = true;
163 continue;
164 }
165 if (!strcmp(arg, "p") || !strcmp(arg, "parse-number-f64")) {
166 g_flags.parse_number_f64 = true;
167 continue;
168 }
169 if (!strcmp(arg, "r") || !strcmp(arg, "render-number-f64")) {
170 g_flags.render_number_f64 = true;
171 continue;
172 }
173
174 return "main: unrecognized flag argument";
175 }
176
177 g_flags.remaining_argc = argc - c;
178 g_flags.remaining_argv = argv + c;
179 return NULL;
180}
181
182const char* //
183main1(int argc, char** argv) {
184 TRY(parse_flags(argc, argv));
185 if (g_flags.remaining_argc > 0) {
186 return "main: bad argument: use \"program < input\", not \"program input\"";
187 }
188
189 uint8_t new_line[1];
190 new_line[0] = '\n';
191
192 g_src = wuffs_base__make_io_buffer(
193 wuffs_base__make_slice_u8(g_src_buffer_array, SRC_BUFFER_ARRAY_SIZE),
194 wuffs_base__empty_io_buffer_meta());
195
196 g_tok = wuffs_base__make_token_buffer(
197 wuffs_base__make_slice_token(g_tok_buffer_array, TOKEN_BUFFER_ARRAY_SIZE),
198 wuffs_base__empty_token_buffer_meta());
199
200 wuffs_base__status init_status = wuffs_json__decoder__initialize(
201 &g_dec, sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
202 if (!wuffs_base__status__is_ok(&init_status)) {
203 return wuffs_base__status__message(&init_status);
204 }
205
206 uint64_t pos = 0;
207 while (true) {
208 wuffs_base__status status = wuffs_json__decoder__decode_tokens(
209 &g_dec, &g_tok, &g_src,
210 wuffs_base__make_slice_u8(g_work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
211
212 while (g_tok.meta.ri < g_tok.meta.wi) {
213 wuffs_base__token* t = &g_tok.data.ptr[g_tok.meta.ri++];
214 uint64_t len = wuffs_base__token__length(t);
215
216 if (wuffs_base__token__value_base_category(t) ==
217 WUFFS_BASE__TOKEN__VBC__NUMBER) {
218 uint64_t buf_pos = pos - g_src.meta.pos;
219 uint64_t buf_len = g_src.data.len;
220 if ((buf_len < buf_pos) || ((buf_len - buf_pos) < len)) {
221 return "main: internal error: inconsistent token position/length";
222 }
223
224 if (g_flags.emit_number_str) {
225 const int stdout_fd = 1;
226 ignore_return_value(write(stdout_fd, &g_src.data.ptr[buf_pos], len));
227 ignore_return_value(write(stdout_fd, &new_line[0], 1));
228 }
229
230 if (g_flags.parse_number_f64) {
231 wuffs_base__result_f64 r = wuffs_base__parse_number_f64(
Nigel Tao6b7ce302020-07-07 16:19:46 +1000232 wuffs_base__make_slice_u8(&g_src.data.ptr[buf_pos], len),
233 WUFFS_BASE__PARSE_NUMBER_XXX__DEFAULT_OPTIONS);
Nigel Tao0eee2312020-07-03 12:48:37 +1000234 if (!wuffs_base__status__is_ok(&r.status)) {
235 return wuffs_base__status__message(&r.status);
236 }
237
238 if (g_flags.render_number_f64) {
239 uint8_t render_buffer[2048];
240 size_t n = wuffs_base__render_number_f64(
241 wuffs_base__make_slice_u8(&render_buffer[0], 2048), r.value, 0,
242 WUFFS_BASE__RENDER_NUMBER_FXX__JUST_ENOUGH_PRECISION);
243 if (n == 0) {
244 return "main: internal error: couldn't render_number_f64";
245 }
246 }
247 }
248 }
249
250 pos += len;
251 if (0 > ((int64_t)pos)) {
252 return "main: input is too long";
253 }
254 }
255
256 if (status.repr == NULL) {
257 return NULL;
258 } else if (status.repr == wuffs_base__suspension__short_read) {
259 TRY(read_src());
260 } else if (status.repr == wuffs_base__suspension__short_write) {
261 wuffs_base__token_buffer__compact(&g_tok);
262 } else {
263 return wuffs_base__status__message(&status);
264 }
265 }
266}
267
268// ----
269
270int //
271compute_exit_code(const char* status_msg) {
272 if (!status_msg) {
273 return 0;
274 }
275 size_t n = strnlen(status_msg, 2047);
276 if (n >= 2047) {
277 status_msg = "main: internal error: error message is too long";
278 n = strnlen(status_msg, 2047);
279 }
280 fprintf(stderr, "%s\n", status_msg);
281 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
282 // formatted or unsupported input.
283 //
284 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
285 // run-time checks found that an internal invariant did not hold.
286 //
287 // Automated testing, including badly formatted inputs, can therefore
288 // discriminate between expected failure (exit code 1) and unexpected failure
289 // (other non-zero exit codes). Specifically, exit code 2 for internal
290 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
291 // linux) for a segmentation fault (e.g. null pointer dereference).
292 return strstr(status_msg, "internal error:") ? 2 : 1;
293}
294
295int //
296main(int argc, char** argv) {
297 const char* z = main1(argc, argv);
298 int exit_code = compute_exit_code(z);
299 return exit_code;
300}