-
Notifications
You must be signed in to change notification settings - Fork 0
/
binario.cpp
102 lines (78 loc) · 2.2 KB
/
binario.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "binario.h"
bio::BinaryBuffer::BinaryBuffer() : buffer_size{bio::BinaryBuffer::defaults::buffer_size}
{
buffer = new char[buffer_size];
};
bio::BinaryBuffer::BinaryBuffer(size_t size) : buffer_size{size}
{
buffer = new char[buffer_size];
};
bio::BinaryBuffer::BinaryBuffer(const bio::BinaryBuffer& cpy) : bio::BinaryBuffer(cpy.buffer_size)
{
std::memcpy(buffer, cpy.buffer, buffer_size);
current_index = cpy.current_index;
}
bio::BinaryBuffer::~BinaryBuffer()
{
delete[] buffer;
};
void bio::BinaryBuffer::open(MODE mode, const char* location)
{
current_index = 0;
if(mode == bio::MODE::READ){
file = new std::fstream(location, std::ios::in | std::ios::binary);
read_next();
} else {
file = new std::fstream(location, std::ios::out | std::ios::binary | std::ios::trunc);
}
current_mode = mode;
if(!file)
throw myexcept::exception(__FUNCTION__, "Cannot open file. Maybe it doesn't exist");
file->seekp(std::ios::end);
size = file->tellp();
file->seekp(std::ios::beg);
file->seekg(std::ios::beg);
}
void bio::BinaryBuffer::read_next()
{
if (!file)
throw myexcept::exception(__func__, "No file open to read from");
if(!file->is_open())
throw myexcept::exception(__func__, "No file open to write to");
size_t delta = size - file->tellg();
if (delta <= 0)
throw myexcept::exception(__func__, "No bytes left to read. Reached end of file");
auto r = buffer_size < delta ? buffer_size : delta;
file->read(buffer, r);
if(!file->good())
throw myexcept::exception(__func__, "Failed writing to file");
current_index = 0;
}
void bio::BinaryBuffer::write_next()
{
if(!file)
throw myexcept::exception(__FUNCTION__, "No file to write to or creation failed");
if(!file->is_open())
throw myexcept::exception(__func__, "No file open to write to");
file->write(buffer, current_index);
if(!file->good())
throw myexcept::exception(__func__, "Failed writing to file");
current_index = 0;
}
void bio::BinaryBuffer::finish(){
if(!file)
return;
if(file->is_open() && current_index > 0 && current_mode == bio::MODE::WRITE){
write_next();
}
file->flush();
}
void bio::BinaryBuffer::close(){
if(!file)
return;
if(!file->is_open())
return;
finish();
file->close();
delete file;
}