74 lines
2.3 KiB
C++
74 lines
2.3 KiB
C++
#include "byte_stream.hh"
|
|
|
|
#include <algorithm>
|
|
// Dummy implementation of a flow-controlled in-memory byte stream.
|
|
|
|
// For Lab 0, please replace with a real implementation that passes the
|
|
// automated checks run by `make check_lab0`.
|
|
|
|
// You will need to add private members to the class declaration in `byte_stream.hh`
|
|
|
|
template <typename... Targs>
|
|
void DUMMY_CODE(Targs &&.../* unused */) {}
|
|
|
|
using namespace std;
|
|
|
|
ByteStream::ByteStream(const size_t capacity) { _capacity = capacity; }
|
|
|
|
size_t ByteStream::write(const string &data) {
|
|
size_t remain = this->_capacity - this->_buffer.size();
|
|
size_t written = std::min(remain, data.size());
|
|
for (size_t i = 0; i < written; ++i) {
|
|
_buffer.push_back(data[i]);
|
|
}
|
|
this->_written_count += written;
|
|
return written;
|
|
}
|
|
|
|
//! \param[in] len bytes will be copied from the output side of the buffer
|
|
string ByteStream::peek_output(const size_t len) const {
|
|
string output;
|
|
size_t avail = std::min(len, _buffer.size());
|
|
for (size_t i = 0; i < avail; ++i) {
|
|
output += this->_buffer[i];
|
|
}
|
|
return output;
|
|
}
|
|
|
|
//! \param[in] len bytes will be removed from the output side of the buffer
|
|
void ByteStream::pop_output(const size_t len) {
|
|
size_t avail = std::min(len, _buffer.size());
|
|
for (size_t i = 0; i < avail; ++i) {
|
|
this->_buffer.pop_front();
|
|
}
|
|
this->_read_count += avail;
|
|
// the test case is more or less stupid here
|
|
// it expects read count be updated on return of `pop_output`
|
|
// rather than `read`
|
|
}
|
|
|
|
//! Read (i.e., copy and then pop) the next "len" bytes of the stream
|
|
//! \param[in] len bytes will be popped and returned
|
|
//! \returns a string
|
|
std::string ByteStream::read(const size_t len) {
|
|
std::string data_read = peek_output(len);
|
|
pop_output(len);
|
|
return data_read;
|
|
}
|
|
|
|
void ByteStream::end_input() { this->_ended = true; }
|
|
|
|
bool ByteStream::input_ended() const { return this->_ended; }
|
|
|
|
size_t ByteStream::buffer_size() const { return this->_buffer.size(); }
|
|
|
|
bool ByteStream::buffer_empty() const { return this->_buffer.empty(); }
|
|
|
|
bool ByteStream::eof() const { return (this->_ended && buffer_empty()); }
|
|
|
|
size_t ByteStream::bytes_written() const { return this->_written_count; }
|
|
|
|
size_t ByteStream::bytes_read() const { return this->_read_count; }
|
|
|
|
size_t ByteStream::remaining_capacity() const { return this->_capacity - this->_buffer.size(); }
|