From 05cc59921ae1439f9546761b266117792b8ba43b Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 4 Jul 2019 06:43:30 +0200 Subject: [PATCH] AK: Start fleshing out LogStream, a type-aware logging mechanism. The first implementation class is DebugLogStream, which can be used like so: dbg() << "Hello friends, I am " << m_years << " years old!"; Note that it will automatically print a newline when the object created by dbg() goes out of scope. This API will grow and evolve, so let's see what we end up with :^) --- AK/LogStream.h | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 AK/LogStream.h diff --git a/AK/LogStream.h b/AK/LogStream.h new file mode 100644 index 0000000000..315d133b79 --- /dev/null +++ b/AK/LogStream.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include + +class LogStream { +public: + LogStream() {} + virtual ~LogStream() {} + + virtual void write(const char*, int) const = 0; +}; + +class DebugLogStream final : public LogStream { +public: + DebugLogStream() {} + virtual ~DebugLogStream() override + { + char newline = '\n'; + write(&newline, 1); + } + + virtual void write(const char* characters, int length) const override + { + for (int i = 0; i < length; ++i) + dbgprintf("%c", characters[i]); + } +}; + +inline DebugLogStream dbg() +{ + return {}; +} + +inline const LogStream& operator<<(const LogStream& stream, const char* value) +{ + stream.write(value, strlen(value)); + return stream; +} + +inline const LogStream& operator<<(const LogStream& stream, const String& value) +{ + stream.write(value.characters(), value.length()); + return stream; +} + +inline const LogStream& operator<<(const LogStream& stream, const StringView& value) +{ + stream.write(value.characters(), value.length()); + return stream; +} + +inline const LogStream& operator<<(const LogStream& stream, char value) +{ + stream.write(&value, 1); + return stream; +} + +inline const LogStream& operator<<(const LogStream& stream, bool value) +{ + return stream << (value ? "true" : "false"); +} + +inline const LogStream& operator<<(const LogStream& stream, int value) +{ + return stream << String::number(value); +} + +inline const LogStream& operator<<(const LogStream& stream, unsigned value) +{ + return stream << String::number(value); +} + +inline const LogStream& operator<<(const LogStream& stream, const void* value) +{ + return stream << String::format("%p", value); +}