From 7efd2a6d59d1de38d0b0ae83415589a08b30f8d9 Mon Sep 17 00:00:00 2001 From: asynts Date: Tue, 1 Sep 2020 16:16:32 +0200 Subject: [PATCH] AK: Add OutputMemoryStream class. --- AK/Forward.h | 2 ++ AK/MemoryStream.h | 16 ++++++++++++++++ AK/Tests/TestMemoryStream.cpp | 11 +++++++++++ 3 files changed, 29 insertions(+) diff --git a/AK/Forward.h b/AK/Forward.h index 1f2c47cd66..6550f7d39f 100644 --- a/AK/Forward.h +++ b/AK/Forward.h @@ -53,6 +53,7 @@ class InputMemoryStream; class DuplexMemoryStream; class OutputStream; class InputBitStream; +class OutputMemoryStream; template class CircularDuplexStream; @@ -150,6 +151,7 @@ using AK::LogStream; using AK::NonnullOwnPtr; using AK::NonnullRefPtr; using AK::Optional; +using AK::OutputMemoryStream; using AK::OutputStream; using AK::OwnPtr; using AK::ReadonlyBytes; diff --git a/AK/MemoryStream.h b/AK/MemoryStream.h index dc8818698e..b8bc5577ce 100644 --- a/AK/MemoryStream.h +++ b/AK/MemoryStream.h @@ -308,8 +308,24 @@ private: size_t m_base_offset { 0 }; }; +class OutputMemoryStream final : public OutputStream { +public: + size_t write(ReadonlyBytes bytes) override { return m_stream.write(bytes); } + bool write_or_error(ReadonlyBytes bytes) override { return m_stream.write_or_error(bytes); } + + ByteBuffer copy_into_contiguous_buffer() const { return m_stream.copy_into_contiguous_buffer(); } + + Optional offset_of(ReadonlyBytes value) const { return m_stream.offset_of(value); } + + size_t size() const { return m_stream.woffset(); } + +private: + DuplexMemoryStream m_stream; +}; + } using AK::DuplexMemoryStream; using AK::InputMemoryStream; using AK::InputStream; +using AK::OutputMemoryStream; diff --git a/AK/Tests/TestMemoryStream.cpp b/AK/Tests/TestMemoryStream.cpp index 611b24ef60..61e8266af4 100644 --- a/AK/Tests/TestMemoryStream.cpp +++ b/AK/Tests/TestMemoryStream.cpp @@ -160,4 +160,15 @@ TEST_CASE(read_endian_values) EXPECT_EQ(value2, 0x04050607u); } +TEST_CASE(write_endian_values) +{ + const u8 expected[] { 4, 3, 2, 1, 1, 2, 3, 4 }; + + OutputMemoryStream stream; + stream << LittleEndian { 0x01020304 } << BigEndian { 0x01020304 }; + + EXPECT_EQ(stream.size(), 8u); + EXPECT(compare({ expected, sizeof(expected) }, stream.copy_into_contiguous_buffer())); +} + TEST_MAIN(MemoryStream)