serenity/AK/MemoryStream.h
Tim Schumacher d5871f5717 AK: Rename Stream::{read,write} to Stream::{read_some,write_some}
Similar to POSIX read, the basic read and write functions of AK::Stream
do not have a lower limit of how much data they read or write (apart
from "none at all").

Rename the functions to "read some [data]" and "write some [data]" (with
"data" being omitted, since everything here is reading and writing data)
to make them sufficiently distinct from the functions that ensure to
use the entire buffer (which should be the go-to function for most
usages).

No functional changes, just a lot of new FIXMEs.
2023-03-13 15:16:20 +00:00

79 lines
2.3 KiB
C++

/*
* Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/OwnPtr.h>
#include <AK/Stream.h>
#include <AK/Vector.h>
namespace AK {
/// A stream class that allows for reading/writing on a preallocated memory area
/// using a single read/write head.
class FixedMemoryStream final : public SeekableStream {
public:
explicit FixedMemoryStream(Bytes bytes);
explicit FixedMemoryStream(ReadonlyBytes bytes);
virtual bool is_eof() const override;
virtual bool is_open() const override;
virtual void close() override;
virtual ErrorOr<void> truncate(size_t) override;
virtual ErrorOr<Bytes> read_some(Bytes bytes) override;
virtual ErrorOr<size_t> seek(i64 offset, SeekMode seek_mode = SeekMode::SetPosition) override;
virtual ErrorOr<size_t> write_some(ReadonlyBytes bytes) override;
virtual ErrorOr<void> write_entire_buffer(ReadonlyBytes bytes) override;
Bytes bytes();
ReadonlyBytes bytes() const;
size_t offset() const;
size_t remaining() const;
private:
Bytes m_bytes;
size_t m_offset { 0 };
bool m_writing_enabled { true };
};
/// A stream class that allows for writing to an automatically allocating memory area
/// and reading back the written data afterwards.
class AllocatingMemoryStream final : public Stream {
public:
virtual ErrorOr<Bytes> read_some(Bytes) override;
virtual ErrorOr<size_t> write_some(ReadonlyBytes) override;
virtual ErrorOr<void> discard(size_t) override;
virtual bool is_eof() const override;
virtual bool is_open() const override;
virtual void close() override;
size_t used_buffer_size() const;
ErrorOr<Optional<size_t>> offset_of(ReadonlyBytes needle) const;
private:
// Note: We set the inline buffer capacity to zero to make moving chunks as efficient as possible.
using Chunk = AK::Detail::ByteBuffer<0>;
static constexpr size_t chunk_size = 4096;
ErrorOr<ReadonlyBytes> next_read_range();
ErrorOr<Bytes> next_write_range();
void cleanup_unused_chunks();
Vector<Chunk> m_chunks;
size_t m_read_offset = 0;
size_t m_write_offset = 0;
};
}
#if USING_AK_GLOBALLY
using AK::AllocatingMemoryStream;
using AK::FixedMemoryStream;
#endif