summaryrefslogtreecommitdiff
path: root/lib/Buffer.cc
blob: 2c2c955ca3e70d4a20edcc6e73cc38a14deff1e1 (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
76
77
#include <string.h>
#include "Buffer.h"
#include "General.h"
#include "config.h"

Buffer::Buffer() : Handle(-1), buffer(0), realsiz(0), bufsiz(0), ptr(0) { }

Buffer::~Buffer() {
    free(buffer);
}

ssize_t Buffer::write(const void *buf, size_t count) {
    if (!count) {
	return 0;
    }
    if (count + realsiz > bufsiz) {
	int numblocks = (count + realsiz) / realloc_threshold;
	int remains = (count + realsiz) % realloc_threshold;
	buffer = (char *) realloc(buffer, bufsiz = ((numblocks + (remains ? 1 : 0)) * realloc_threshold));
    }
    memcpy(buffer + realsiz, buf, count);
    realsiz += count;
    
    return count;
}

ssize_t Buffer::read(void *buf, size_t count) throw (GeneralException) {
    count = MIN(count, realsiz - ptr);

    if (!count) {
	return 0;
    }
    
    memcpy(buf, buffer + ptr, count);
    ptr += count;
    
    if (ptr >= realloc_threshold) {
	int numblocks = (bufsiz / realloc_threshold) - (ptr / realloc_threshold);
	memmove(buffer, buffer + (bufsiz - numblocks * realloc_threshold), numblocks * realloc_threshold);
	ptr -= (bufsiz - numblocks * realloc_threshold);
	realsiz -= (bufsiz - numblocks * realloc_threshold);
	buffer = (char *) realloc(buffer, bufsiz = (numblocks * realloc_threshold));
    }
    
    return count;
}

bool Buffer::CanRead() {
    return true;
}

bool Buffer::CanWrite() {
    return true;
}

String Buffer::GetName() {
    return "Buffer";
}

Buffer Buffer::operator=(const Buffer & b) {
    if (b.buffer != buffer) {
	free(buffer);
	realsiz = b.realsiz;
	ptr = b.ptr;
	if ((bufsiz = b.bufsiz)) {
	    buffer = (char *) malloc(bufsiz);
	    memcpy(buffer, b.buffer, realsiz);
	} else {
	    buffer = 0;
	}
    }
    return *this;
}

bool Buffer::CanWatch() {
    return false;
}