2 * *****************************************************************************
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2018-2023 Gavin D. Howard and contributors.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
30 * *****************************************************************************
32 * Code for implementing buffered I/O on my own terms.
47 #if !BC_ENABLE_LINE_LIB
50 * Translates an integer into a string.
51 * @param val The value to translate.
52 * @param buf The return parameter.
55 bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH])
57 char buf2[BC_FILE_ULL_LENGTH];
60 // We need to make sure the entire thing is zeroed.
62 memset(buf2, 0, BC_FILE_ULL_LENGTH);
64 // The i = 1 is to ensure that there is a null byte at the end.
67 unsigned long long mod = val % 10;
69 buf2[i] = ((char) mod) + '0';
75 // Since buf2 is reversed, reverse it into buf.
76 for (i = 0; i < len; ++i)
78 buf[i] = buf2[len - i - 1];
83 * Output to the file directly.
84 * @param fd The file descriptor.
85 * @param buf The buffer of data to output.
86 * @param n The number of bytes to output.
87 * @return A status indicating error or success. We could have a fatal I/O
91 bc_file_output(int fd, const char* buf, size_t n)
98 // While the number of bytes written is less than intended...
102 ssize_t written = write(fd, buf + bytes, n - bytes);
104 // Check for error and return, if any.
105 if (BC_ERR(written == -1))
107 BC_SIG_TRYUNLOCK(lock);
109 return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL;
112 bytes += (size_t) written;
115 BC_SIG_TRYUNLOCK(lock);
117 return BC_STATUS_SUCCESS;
120 #endif // !BC_ENABLE_LINE_LIB
123 bc_file_flushErr(BcFile* restrict f, BcFlushType type)
127 BC_SIG_ASSERT_LOCKED;
129 #if BC_ENABLE_LINE_LIB
131 // Just flush and propagate the error.
132 if (fflush(f->f) == EOF) s = BC_STATUS_ERROR_FATAL;
133 else s = BC_STATUS_SUCCESS;
135 #else // BC_ENABLE_LINE_LIB
137 // If there is stuff to output...
140 #if BC_ENABLE_HISTORY
142 // If history is enabled...
145 // If we have been told to save the extras, and there *are*
147 if (f->buf[f->len - 1] != '\n' &&
148 (type == BC_FLUSH_SAVE_EXTRAS_CLEAR ||
149 type == BC_FLUSH_SAVE_EXTRAS_NO_CLEAR))
153 // Look for the last newline.
154 for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i)
162 bc_vec_string(&vm->history.extras, f->len - i, f->buf + i);
164 // Else clear the extras if told to.
165 else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR)
167 bc_vec_popAll(&vm->history.extras);
170 #endif // BC_ENABLE_HISTORY
173 s = bc_file_output(f->fd, f->buf, f->len);
176 else s = BC_STATUS_SUCCESS;
178 #endif // BC_ENABLE_LINE_LIB
184 bc_file_flush(BcFile* restrict f, BcFlushType type)
189 BC_SIG_TRYLOCK(lock);
191 s = bc_file_flushErr(f, type);
193 // If we have an error...
196 // For EOF, set it and jump.
197 if (s == BC_STATUS_EOF)
199 vm->status = (sig_atomic_t) s;
200 BC_SIG_TRYUNLOCK(lock);
203 // Blow up on fatal error. Okay, not blow up, just quit.
204 else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
207 BC_SIG_TRYUNLOCK(lock);
210 #if !BC_ENABLE_LINE_LIB
213 bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n)
217 BC_SIG_TRYLOCK(lock);
219 // If we have enough to flush, do it.
220 if (n > f->cap - f->len)
222 bc_file_flush(f, type);
226 // If the output is large enough to flush by itself, just output it.
227 // Otherwise, put it into the buffer.
228 if (BC_UNLIKELY(n > f->cap - f->len))
230 BcStatus s = bc_file_output(f->fd, buf, n);
234 // For EOF, set it and jump.
235 if (s == BC_STATUS_EOF)
237 vm->status = (sig_atomic_t) s;
238 BC_SIG_TRYUNLOCK(lock);
241 // Blow up on fatal error. Okay, not blow up, just quit.
242 else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
248 memcpy(f->buf + f->len, buf, n);
252 BC_SIG_TRYUNLOCK(lock);
255 #endif // BC_ENABLE_LINE_LIB
258 bc_file_printf(BcFile* restrict f, const char* fmt, ...)
263 BC_SIG_TRYLOCK(lock);
266 bc_file_vprintf(f, fmt, args);
269 BC_SIG_TRYUNLOCK(lock);
273 bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args)
275 BC_SIG_ASSERT_LOCKED;
277 #if BC_ENABLE_LINE_LIB
282 // This mess is to silence a warning.
284 #pragma clang diagnostic ignored "-Wformat-nonliteral"
286 r = vfprintf(f->f, fmt, args);
288 #pragma clang diagnostic warning "-Wformat-nonliteral"
291 // Just print and propagate the error.
294 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
298 #else // BC_ENABLE_LINE_LIB
302 const char* ptr = fmt;
303 char buf[BC_FILE_ULL_LENGTH];
305 // This is a poor man's printf(). While I could look up algorithms to
306 // make it as fast as possible, and should when I write the standard
307 // library for a new language, for bc, outputting is not the bottleneck.
308 // So we cheese it for now.
310 // Find each percent sign.
311 while ((percent = strchr(ptr, '%')) != NULL)
315 // If the percent sign is not where we are, write what's inbetween
319 size_t len = (size_t) (percent - ptr);
320 bc_file_write(f, bc_flush_none, ptr, len);
325 // We only parse some format specifiers, the ones bc uses. If you
326 // add more, you need to make sure to add them here.
329 uchar uc = (uchar) va_arg(args, int);
331 bc_file_putchar(f, bc_flush_none, uc);
335 char* s = va_arg(args, char*);
337 bc_file_puts(f, bc_flush_none, s);
340 // We only print signed integers in debug code.
343 int d = va_arg(args, int);
345 // Take care of negative. Let's not worry about overflow.
348 bc_file_putchar(f, bc_flush_none, '-');
352 // Either print 0 or translate and print.
353 if (!d) bc_file_putchar(f, bc_flush_none, '0');
356 bc_file_ultoa((unsigned long long) d, buf);
357 bc_file_puts(f, bc_flush_none, buf);
363 unsigned long long ull;
365 // These are the ones that it expects from here. Fortunately,
366 // all of these are unsigned types, so they can use the same
367 // code, more or less.
368 assert((c == 'l' || c == 'z') && percent[2] == 'u');
370 if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
371 else ull = (unsigned long long) va_arg(args, unsigned long);
373 // Either print 0 or translate and print.
374 if (!ull) bc_file_putchar(f, bc_flush_none, '0');
377 bc_file_ultoa(ull, buf);
378 bc_file_puts(f, bc_flush_none, buf);
382 // Increment to the next spot after the specifier.
383 ptr = percent + 2 + (c == 'l' || c == 'z');
386 // If we get here, there are no more percent signs, so we just output
388 if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
391 #endif // BC_ENABLE_LINE_LIB
395 bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str)
397 #if BC_ENABLE_LINE_LIB
398 // This is used because of flushing issues with using bc_file_write() when
399 // bc is using a line library. It's also using printf() because puts()
401 bc_file_printf(f, "%s", str);
402 #else // BC_ENABLE_LINE_LIB
403 bc_file_write(f, type, str, strlen(str));
404 #endif // BC_ENABLE_LINE_LIB
408 bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c)
412 BC_SIG_TRYLOCK(lock);
414 #if BC_ENABLE_LINE_LIB
416 if (BC_ERR(fputc(c, f->f) == EOF))
418 // This is here to prevent a stack overflow from unbounded recursion.
419 if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL);
421 bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
424 #else // BC_ENABLE_LINE_LIB
426 if (f->len == f->cap) bc_file_flush(f, type);
428 assert(f->len < f->cap);
430 f->buf[f->len] = (char) c;
433 #endif // BC_ENABLE_LINE_LIB
435 BC_SIG_TRYUNLOCK(lock);
438 #if BC_ENABLE_LINE_LIB
441 bc_file_init(BcFile* f, FILE* file)
443 BC_SIG_ASSERT_LOCKED;
447 #else // BC_ENABLE_LINE_LIB
450 bc_file_init(BcFile* f, int fd, char* buf, size_t cap)
452 BC_SIG_ASSERT_LOCKED;
460 #endif // BC_ENABLE_LINE_LIB
463 bc_file_free(BcFile* f)
465 BC_SIG_ASSERT_LOCKED;
466 bc_file_flush(f, bc_flush_none);