add memory_istream

This commit is contained in:
MihailRis 2025-02-22 05:47:27 +03:00
parent 8a8c1525fd
commit decb820cf9
2 changed files with 53 additions and 0 deletions

34
src/io/memory_istream.hpp Normal file
View File

@ -0,0 +1,34 @@
#pragma once
#include <istream>
#include "util/Buffer.hpp"
class memory_istream : public std::istream {
public:
explicit memory_istream(util::Buffer<char> buffer)
: std::istream(&buf), buf(std::move(buffer)) {}
private:
class memory_streambuf : public std::streambuf {
public:
explicit memory_streambuf(util::Buffer<char> buffer)
: buffer(std::move(buffer)) {
char* base = this->buffer.data();
char* end = base + this->buffer.size();
setg(base, base, end);
}
memory_streambuf(const memory_streambuf&) = delete;
memory_streambuf& operator=(const memory_streambuf&) = delete;
protected:
int_type underflow() override {
return traits_type::eof();
}
private:
util::Buffer<char> buffer;
};
memory_streambuf buf;
};

View File

@ -0,0 +1,19 @@
#include <gtest/gtest.h>
#include "io/memory_istream.hpp"
TEST(io, memory_istream) {
const char data[] = "Hello, world!";
const int n = std::strlen(data);
util::Buffer<char> buffer(data, n);
memory_istream stream(std::move(buffer));
ASSERT_TRUE(stream.good());
std::string text(n, '\0');
stream.read(text.data(), n);
ASSERT_EQ(text, std::string(data));
stream.read(text.data(), 1);
ASSERT_TRUE(stream.eof());
}