forked from livecode/livecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlarge_buffer.h
More file actions
106 lines (85 loc) · 2.25 KB
/
large_buffer.h
File metadata and controls
106 lines (85 loc) · 2.25 KB
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
103
104
105
106
/* Copyright (C) 2003-2015 LiveCode Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#ifndef __LARGE_BUFFER__
#define __LARGE_BUFFER__
#include "stddef.h"
class large_buffer_t
{
public:
large_buffer_t(void)
: m_data(NULL),
m_frontier(NULL),
m_capacity(0)
{
}
~large_buffer_t(void)
{
if (m_data != NULL)
free(m_data);
}
void append(char p_char)
{
append(&p_char, 1);
}
void append(const void *p_data, unsigned int p_length)
{
if (m_frontier - m_data + p_length > m_capacity)
if (!extend(p_length))
return;
memcpy(m_frontier, p_data, p_length);
m_frontier = m_frontier + p_length;
}
void *ptr(void)
{
return m_data;
}
ptrdiff_t length(void)
{
return m_frontier - m_data;
}
void grab(void*& r_data, unsigned int& r_length)
{
r_length = m_frontier - m_data;
r_data = (void *)realloc(m_data, r_length);
m_data = NULL;
m_frontier = NULL;
m_capacity = 0;
}
private:
char *m_data;
char *m_frontier;
unsigned int m_capacity;
bool extend(unsigned int p_amount)
{
unsigned int t_new_capacity;
t_new_capacity = (m_frontier - m_data) + p_amount;
if (t_new_capacity < 4096)
t_new_capacity = (t_new_capacity + 4095) & ~4095;
else if (t_new_capacity < 65536)
t_new_capacity = (t_new_capacity + 65535) & ~65535;
else
t_new_capacity = (t_new_capacity + 1024 * 1024 - 1) & ~(1024 * 1024 - 1);
char *t_new_data;
t_new_data = (char *)realloc(m_data, t_new_capacity);
if (t_new_data == NULL)
{
t_new_data = (char *)realloc(m_data, (m_frontier - m_data) + p_amount);
if (t_new_data == NULL)
return false;
}
m_frontier = t_new_data + (m_frontier - m_data);
m_data = t_new_data;
m_capacity = t_new_capacity;
return true;
}
};
#endif