add memory_istream
This commit is contained in:
parent
8a8c1525fd
commit
decb820cf9
34
src/io/memory_istream.hpp
Normal file
34
src/io/memory_istream.hpp
Normal 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;
|
||||
};
|
||||
19
test/io/memory_istream.cpp
Normal file
19
test/io/memory_istream.cpp
Normal 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());
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user