From a2303665fc2ffe517eafee5995ac343facd546ec Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 1 May 2023 19:31:15 +0200 Subject: [PATCH] libos: Add os:: print(), println(), eprint(), and eprintln() --- libluna/include/luna/String.h | 3 +- libos/include/os/File.h | 5 +++ libos/src/File.cpp | 59 +++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/libluna/include/luna/String.h b/libluna/include/luna/String.h index c8e7000b..2140fffb 100644 --- a/libluna/include/luna/String.h +++ b/libluna/include/luna/String.h @@ -38,6 +38,7 @@ class String static Result format(const String& fmt, ...); static Result format(StringView fmt, ...); + static Result vformat(StringView fmt, va_list ap); static Result from_cstring(const char* str); @@ -94,6 +95,4 @@ class String usize m_length { 0 }; void empty(); - - static Result vformat(StringView fmt, va_list ap); }; diff --git a/libos/include/os/File.h b/libos/include/os/File.h index ab770058..7f9f9156 100644 --- a/libos/include/os/File.h +++ b/libos/include/os/File.h @@ -66,4 +66,9 @@ namespace os int m_fd { -1 }; }; + + Result print(StringView fmt, ...); + Result println(StringView fmt, ...); + Result eprint(StringView fmt, ...); + Result eprintln(StringView fmt, ...); } diff --git a/libos/src/File.cpp b/libos/src/File.cpp index 2f6be82a..33c1dd49 100644 --- a/libos/src/File.cpp +++ b/libos/src/File.cpp @@ -193,4 +193,63 @@ namespace os { fcntl(m_fd, F_SETFD, FD_CLOEXEC); } + + // FIXME: Do not allocate memory for printing. + Result print_impl(SharedPtr f, StringView fmt, va_list ap) + { + auto str = TRY(String::vformat(fmt, ap)); + return f->write(str.view()); + } + + Result print(StringView fmt, ...) + { + va_list ap; + va_start(ap, fmt); + + auto rc = print_impl(File::standard_output(), fmt, ap); + + va_end(ap); + + return rc; + } + + Result println(StringView fmt, ...) + { + va_list ap; + va_start(ap, fmt); + + auto rc = print_impl(File::standard_output(), fmt, ap); + + va_end(ap); + + TRY(rc); + + return File::standard_output()->write("\n"_sv); + } + + Result eprint(StringView fmt, ...) + { + va_list ap; + va_start(ap, fmt); + + auto rc = print_impl(File::standard_error(), fmt, ap); + + va_end(ap); + + return rc; + } + + Result eprintln(StringView fmt, ...) + { + va_list ap; + va_start(ap, fmt); + + auto rc = print_impl(File::standard_error(), fmt, ap); + + va_end(ap); + + TRY(rc); + + return File::standard_error()->write("\n"_sv); + } }