Lock-protected buffered stdout writer with TTY detection and ANSI escape support.
更多...
Lock-protected buffered stdout writer with TTY detection and ANSI escape support.
TerminalStream is a process singleton that funnels formatted output straight into a one-megabyte internal buffer and emits it through raw write() / _write() syscalls. It exists because std::cout's locale conversion, hidden allocations, and per-character mutex traffic dominate the cost of hot-path logging in the VLink runtime.
- Stream modes
| Mode | Trigger | Behaviour |
| Buffered append | write fits in remaining buffer space | append to buffer, no syscall |
| Auto flush | buffer fills or endl is used | drain buffer with write() / _write() |
| Direct passthrough | single write >= kDefaultBufferSize | flush buffer first, then write directly |
| Manual flush | flush() or flush_manip invoked | drain buffer (and tcdrain on POSIX TTYs) |
- ANSI colour cheat-sheet (foreground)
| Sequence | Effect | | Sequence | Effect |
"\x1b[0m" | reset all attributes | | "\x1b[37m" | white |
"\x1b[1m" | bold / bright | | "\x1b[90m" | bright black (grey) |
"\x1b[30m" | black | | "\x1b[91m" | bright red |
"\x1b[31m" | red | | "\x1b[92m" | bright green |
"\x1b[32m" | green | | "\x1b[93m" | bright yellow |
"\x1b[33m" | yellow | | "\x1b[94m" | bright blue |
"\x1b[34m" | blue | | "\x1b[95m" | bright magenta |
"\x1b[35m" | magenta | | "\x1b[96m" | bright cyan |
"\x1b[36m" | cyan | | "\x1b[97m" | bright white |
Background colours follow the same pattern shifted by 10 ("\x1b[40m" -> "\x1b[47m"). Always gate colour emission behind is_tty() so redirected output stays clean.
- Thread safety
- Every public method takes the same internal mutex, so a single
operator<< call cannot interleave with another thread's call. Chained writes (ts << a << b) acquire the mutex per token; wrap the chain in an external lock if cross-token atomicity is required.
- Example
ts.init();
if (ts.is_tty()) {
ts << "\x1b[32m[OK]\x1b[0m ";
} else {
ts << "[OK] ";
}
static TerminalStream & get() noexcept
Returns the process-wide singleton, building it on the first call.
static TerminalStream & endl(TerminalStream &stream) noexcept
Manipulator that appends a newline byte and flushes the buffer.