buffered reader and writer
This commit is contained in:
parent
e50051b8e6
commit
6be1112091
5 changed files with 137 additions and 1 deletions
55
writer.hpp
Normal file
55
writer.hpp
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
#pragma once
|
||||
#include "record.hpp"
|
||||
#include <ostream>
|
||||
#include <vector>
|
||||
|
||||
class Writer {
|
||||
private:
|
||||
std::vector<Record> write_buffer;
|
||||
std::ostream& output_stream;
|
||||
size_t buffer_size;
|
||||
size_t total_writes_count;
|
||||
size_t current_idx; // Current position in buffer
|
||||
|
||||
// returns true on success
|
||||
// doesn't really flush for performace reasons
|
||||
// could be changed to really flush to monitor the impac of amount of writes
|
||||
bool flush_buffer()
|
||||
{
|
||||
for (size_t i = 0; i < current_idx; ++i) {
|
||||
if (!(output_stream << write_buffer[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public:
|
||||
explicit Writer(std::ostream& output_stream, size_t buffer_size = 8)
|
||||
: write_buffer(buffer_size)
|
||||
, output_stream(output_stream)
|
||||
, buffer_size(buffer_size)
|
||||
, total_writes_count(0)
|
||||
, current_idx(0)
|
||||
{
|
||||
}
|
||||
|
||||
bool write(const Record& record)
|
||||
{
|
||||
write_buffer[current_idx] = record;
|
||||
current_idx++;
|
||||
total_writes_count++;
|
||||
|
||||
if (current_idx >= buffer_size) {
|
||||
return flush_buffer();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t total_writes() const
|
||||
{
|
||||
return total_writes_count;
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue