libos: Add os:: print(), println(), eprint(), and eprintln()

This commit is contained in:
apio 2023-05-01 19:31:15 +02:00
parent df590f4e26
commit a2303665fc
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 65 additions and 2 deletions

View File

@ -38,6 +38,7 @@ class String
static Result<String> format(const String& fmt, ...);
static Result<String> format(StringView fmt, ...);
static Result<String> vformat(StringView fmt, va_list ap);
static Result<String> from_cstring(const char* str);
@ -94,6 +95,4 @@ class String
usize m_length { 0 };
void empty();
static Result<String> vformat(StringView fmt, va_list ap);
};

View File

@ -66,4 +66,9 @@ namespace os
int m_fd { -1 };
};
Result<void> print(StringView fmt, ...);
Result<void> println(StringView fmt, ...);
Result<void> eprint(StringView fmt, ...);
Result<void> eprintln(StringView fmt, ...);
}

View File

@ -193,4 +193,63 @@ namespace os
{
fcntl(m_fd, F_SETFD, FD_CLOEXEC);
}
// FIXME: Do not allocate memory for printing.
Result<void> print_impl(SharedPtr<File> f, StringView fmt, va_list ap)
{
auto str = TRY(String::vformat(fmt, ap));
return f->write(str.view());
}
Result<void> 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<void> 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<void> 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<void> 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);
}
}