Make major improvements to stdio

Buffering now has optimal performance, bugs have been fixed, and some
missing apis have been introduced. This implementation is also now more
production worthy since it's less brittle now in terms of system errors.
That's going to help redbean since lua i/o is all based on stdio.

See #97
This commit is contained in:
Justine Tunney 2021-03-26 22:31:41 -07:00
parent 09bcfa23d5
commit da36e7e256
69 changed files with 1595 additions and 735 deletions

View file

@ -64,7 +64,7 @@ void vflogf_onfail(FILE *f) {
struct stat st;
if (IsTiny()) return;
err = ferror(f);
if ((err == ENOSPC || err == EDQUOT || err == EFBIG) &&
if (fileno(f) != -1 && (err == ENOSPC || err == EDQUOT || err == EFBIG) &&
(fstat(fileno(f), &st) == -1 || st.st_size > kNontrivialSize)) {
ftruncate(fileno(f), 0);
fseek(f, SEEK_SET, 0);
@ -91,6 +91,7 @@ void vflogf_onfail(FILE *f) {
*/
void(vflogf)(unsigned level, const char *file, int line, FILE *f,
const char *fmt, va_list va) {
int bufmode;
struct tm tm;
long double t2;
const char *prog;
@ -98,7 +99,7 @@ void(vflogf)(unsigned level, const char *file, int line, FILE *f,
char buf32[32], *buf32p;
int64_t secs, nsec, dots;
if (!f) f = __log_file;
if (fileno(f) == -1) return;
if (!f) return;
t2 = nowl();
secs = t2;
nsec = (t2 - secs) * 1e9L;
@ -114,6 +115,8 @@ void(vflogf)(unsigned level, const char *file, int line, FILE *f,
buf32p = "--------------------";
}
prog = basename(program_invocation_name);
bufmode = f->bufmode;
if (bufmode == _IOLBF) f->bufmode = _IOFBF;
if ((fprintf)(f, "%c%s%06ld:%s:%d:%.*s:%d] ", vflogf_loglevel2char(level),
buf32p, rem1000000int64(div1000int64(dots)), file, line,
strchrnul(prog, '.') - prog, prog, getpid()) <= 0) {
@ -122,6 +125,10 @@ void(vflogf)(unsigned level, const char *file, int line, FILE *f,
(vfprintf)(f, fmt, va);
va_end(va);
fputs("\n", f);
if (bufmode == _IOLBF) {
f->bufmode = _IOLBF;
fflush(f);
}
if (level == kLogFatal) {
__start_fatal(file, line);
strcpy(buf32, "unknown");