实现一个 stream
。
byte_stream.hh
处的修改。
class ByteStream
{
public:
explicit ByteStream( uint64_t capacity );
// Helper functions (provided) to access the ByteStream's Reader and Writer interfaces
Reader& reader();
const Reader& reader() const;
Writer& writer();
const Writer& writer() const;
void set_error() { error_ = true; }; // Signal that the stream suffered an error.
bool has_error() const { return error_; }; // Has the stream had an error?
protected:
// Please add any additional state to the ByteStream here, and not to the Writer and Reader interfaces.
uint64_t count_ = 0; // data buffed
std::queue<std::string> buffer_ {};
uint64_t total_bytes_pushed_ = 0;
uint64_t prefix_ = 0;
bool closed_ {};
uint64_t capacity_;
bool error_ {};
};
byte_stream.cc
处的修改。
void Writer::push( string data )
{
if (is_closed() || available_capacity() == 0 || data.empty()) {
return;
}
if (data.size() > available_capacity()) {
data.resize(available_capacity());
}
count_ += data.size();
total_bytes_pushed_ += data.size();
buffer_.push(std::move(data));
}
void Writer::close()
{
closed_ = true;
}
bool Writer::is_closed() const
{
return closed_;
}
uint64_t Writer::available_capacity() const
{
return capacity_ - count_;
}
uint64_t Writer::bytes_pushed() const
{
return total_bytes_pushed_;
}
string_view Reader::peek() const
{
if (buffer_.empty()) {
return {};
}
return string_view(buffer_.front()).substr(prefix_);
}
void Reader::pop( uint64_t len )
{
while (not buffer_.empty()) {
if (len + prefix_ >= buffer_.front().size()) {
len -= buffer_.front().size() - prefix_;
count_ -= buffer_.front().size() - prefix_;
prefix_ = 0;
buffer_.pop();
} else {
prefix_ += len;
count_ -= len;
break;
}
}
}
bool Reader::is_finished() const
{
return closed_ and count_ == 0;
}
uint64_t Reader::bytes_buffered() const
{
return count_;
}
uint64_t Reader::bytes_popped() const
{
return total_bytes_pushed_ - count_;
}
Comments NOTHING