blob: a9585716036619eab9a51975ebb80307855a893d (
plain)
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
|
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "Buffer.h"
#include "Task.h"
#include "Printer.h"
static const int s_blockSize = 16 * 1024;
Balau::Buffer::~Buffer() {
if (!m_fromConst)
free(m_buffer);
}
void Balau::Buffer::close() throw (GeneralException) {
reset();
}
ssize_t Balau::Buffer::read(void * buf, size_t count) throw (GeneralException) {
off_t cursor = rtell();
if (cursor >= m_bufSize)
return 0;
off_t avail = m_bufSize - cursor;
if (count > avail)
count = avail;
memcpy(buf, m_buffer + cursor, count);
rseek(cursor + count);
return count;
}
ssize_t Balau::Buffer::write(const void * buf, size_t count) throw (GeneralException) {
if (m_fromConst)
throw GeneralException("Buffer is read only and can't be written to.");
off_t cursor = wtell();
off_t end = cursor + count;
off_t endBlock = (end / s_blockSize) + ((end % s_blockSize) ? 1 : 0);
off_t oldEndBlock = m_numBlocks;
if (endBlock > oldEndBlock) {
m_buffer = (uint8_t *) realloc(m_buffer, endBlock * s_blockSize);
memset(m_buffer + oldEndBlock * s_blockSize, 0, (endBlock - oldEndBlock) * s_blockSize);
m_numBlocks = endBlock;
}
memcpy(m_buffer + cursor, buf, count);
wseek(cursor + count);
if (m_bufSize < end)
m_bufSize = end;
return count;
}
void Balau::Buffer::reset() {
m_buffer = (uint8_t *) realloc(m_buffer, 0);
m_bufSize = 0;
m_numBlocks = 0;
wseek(0);
rseek(0);
}
bool Balau::Buffer::isClosed() { return false; }
bool Balau::Buffer::isEOF() { return rtell() == m_bufSize; }
const char * Balau::Buffer::getName() { return "Buffer"; }
off_t Balau::Buffer::getSize() { return m_bufSize; }
bool Balau::Buffer::canRead() { return true; }
bool Balau::Buffer::canWrite() { return !m_fromConst; }
|