summaryrefslogtreecommitdiff
path: root/indra/llcorehttp/bufferarray.cpp
blob: 8d2e7c6a63b6fb17a586e6091e44f2917c6c4b74 (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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/**
 * @file bufferarray.cpp
 * @brief Implements the BufferArray scatter/gather buffer
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "bufferarray.h"
#include "llexception.h"
#include "llmemory.h"


// BufferArray is a list of chunks, each a BufferArray::Block, of contiguous
// data presented as a single array.  Chunks are at least BufferArray::BLOCK_ALLOC_SIZE
// in length and can be larger.  Any chunk may be partially filled or even
// empty.
//
// The BufferArray itself is sharable as a RefCounted entity.  As shared
// reads don't work with the concept of a current position/seek value,
// none is kept with the object.  Instead, the read and write operations
// all take position arguments.  Single write/shared read isn't supported
// directly and any such attempts have to be serialized outside of this
// implementation.

namespace LLCore
{


// ==================================
// BufferArray::Block Declaration
// ==================================

class BufferArray::Block
{
public:
	~Block();

	void operator delete(void *);
	void operator delete(void *, size_t len);

protected:
	Block(size_t len);

	Block(const Block &);						// Not defined
	void operator=(const Block &);				// Not defined

	// Allocate the block with the additional space for the
	// buffered data at the end of the object.
	void * operator new(size_t len, size_t addl_len);
	
public:
	// Only public entry to get a block.
	static Block * alloc(size_t len);

public:
	size_t mUsed;
	size_t mAlloced;

	// *NOTE:  Must be last member of the object.  We'll
	// overallocate as requested via operator new and index
	// into the array at will.
	char mData[1];		
};


// ==================================
// BufferArray Definitions
// ==================================


#if	! LL_WINDOWS
const size_t BufferArray::BLOCK_ALLOC_SIZE;
#endif	// ! LL_WINDOWS

BufferArray::BufferArray()
	: LLCoreInt::RefCounted(true),
	  mLen(0)
{}


BufferArray::~BufferArray()
{
	for (container_t::iterator it(mBlocks.begin());
		 it != mBlocks.end();
		 ++it)
	{
		delete *it;
		*it = NULL;
	}
	mBlocks.clear();
}


size_t BufferArray::append(const void * src, size_t len)
{
	const size_t ret(len);
	const char * c_src(static_cast<const char *>(src));
					  
	// First, try to copy into the last block
	if (len && ! mBlocks.empty())
	{
		Block & last(*mBlocks.back());
		if (last.mUsed < last.mAlloced)
		{
			// Some will fit...
			const size_t copy_len((std::min)(len, (last.mAlloced - last.mUsed)));

			memcpy(&last.mData[last.mUsed], c_src, copy_len);
			last.mUsed += copy_len;
			llassert_always(last.mUsed <= last.mAlloced);
			mLen += copy_len;
			c_src += copy_len;
			len -= copy_len;
		}
	}

	// Then get new blocks as needed
	while (len)
	{
		const size_t copy_len((std::min)(len, BLOCK_ALLOC_SIZE));
		
		if (mBlocks.size() >= mBlocks.capacity())
		{
			mBlocks.reserve(mBlocks.size() + 5);
		}
        Block * block;
        try
        {
            block = Block::alloc(BLOCK_ALLOC_SIZE);
        }
        catch (std::bad_alloc&)
        {
            LLMemory::logMemoryInfo(TRUE);

            //output possible call stacks to log file.
            LLError::LLCallStacks::print();

            LL_WARNS() << "Bad memory allocation in thrown by Block::alloc in read!" << LL_ENDL;
            break;
        }
        memcpy(block->mData, c_src, copy_len);
		block->mUsed = copy_len;
		llassert_always(block->mUsed <= block->mAlloced);
		mBlocks.push_back(block);
		mLen += copy_len;
		c_src += copy_len;
		len -= copy_len;
	}
	return ret - len;
}


void * BufferArray::appendBufferAlloc(size_t len)
{
	// If someone asks for zero-length, we give them a valid pointer.
	if (mBlocks.size() >= mBlocks.capacity())
	{
		mBlocks.reserve(mBlocks.size() + 5);
	}
	Block * block = Block::alloc((std::max)(BLOCK_ALLOC_SIZE, len));
	block->mUsed = len;
	mBlocks.push_back(block);
	mLen += len;
	return block->mData;
}


size_t BufferArray::read(size_t pos, void * dst, size_t len)
{
	char * c_dst(static_cast<char *>(dst));
	
	if (pos >= mLen)
		return 0;
	size_t len_limit(mLen - pos);
	len = (std::min)(len, len_limit);
	if (0 == len)
		return 0;
	
	size_t result(0), offset(0);
	const auto block_limit(mBlocks.size());
	int block_start(findBlock(pos, &offset));
	if (block_start < 0)
		return 0;

	do
	{
		Block & block(*mBlocks[block_start]);
		size_t block_limit(block.mUsed - offset);
		size_t block_len((std::min)(block_limit, len));
		
		memcpy(c_dst, &block.mData[offset], block_len);
		result += block_len;
		len -= block_len;
		c_dst += block_len;
		offset = 0;
		++block_start;
	}
	while (len && block_start < block_limit);

	return result;
}


size_t BufferArray::write(size_t pos, const void * src, size_t len)
{
	const char * c_src(static_cast<const char *>(src));
	
	if (pos > mLen || 0 == len)
		return 0;
	
	size_t result(0), offset(0);
	const auto block_limit(mBlocks.size());
	int block_start(findBlock(pos, &offset));

	if (block_start >= 0)
	{
		// Some or all of the write will be on top of
		// existing data.
		do
		{
			Block & block(*mBlocks[block_start]);
			size_t block_limit(block.mUsed - offset);
			size_t block_len((std::min)(block_limit, len));
		
			memcpy(&block.mData[offset], c_src, block_len);
			result += block_len;
			c_src += block_len;
			len -= block_len;
			offset = 0;
			++block_start;
		}
		while (len && block_start < block_limit);
	}

	// Something left, see if it will fit in the free
	// space of the last block.
	if (len && ! mBlocks.empty())
	{
		Block & last(*mBlocks.back());
		if (last.mUsed < last.mAlloced)
		{
			// Some will fit...
			const size_t copy_len((std::min)(len, (last.mAlloced - last.mUsed)));

			memcpy(&last.mData[last.mUsed], c_src, copy_len);
			last.mUsed += copy_len;
			result += copy_len;
			llassert_always(last.mUsed <= last.mAlloced);
			mLen += copy_len;
			c_src += copy_len;
			len -= copy_len;
		}
	}
	
	if (len)
	{
		// Some or all of the remaining write data will
		// be an append.
		result += append(c_src, len);
	}

	return result;
}
		

int BufferArray::findBlock(size_t pos, size_t * ret_offset)
{
	*ret_offset = 0;
	if (pos >= mLen)
		return -1;		// Doesn't exist

	const int block_limit(narrow(mBlocks.size()));
	for (int i(0); i < block_limit; ++i)
	{
		if (pos < mBlocks[i]->mUsed)
		{
			*ret_offset = pos;
			return i;
		}
		pos -= mBlocks[i]->mUsed;
	}

	// Shouldn't get here but...
	return -1;
}


bool BufferArray::getBlockStartEnd(int block, const char ** start, const char ** end)
{
	if (block < 0 || block >= mBlocks.size())
	{
		return false;
	}

	const Block & b(*mBlocks[block]);
	*start = &b.mData[0];
	*end = &b.mData[b.mUsed];
	return true;
}


// ==================================
// BufferArray::Block Definitions
// ==================================


BufferArray::Block::Block(size_t len)
	: mUsed(0),
	  mAlloced(len)
{
	memset(mData, 0, len);
}
			

BufferArray::Block::~Block()
{
	mUsed = 0;
	mAlloced = 0;
}


void * BufferArray::Block::operator new(size_t len, size_t addl_len)
{
	void * mem = new char[len + addl_len + sizeof(void *)];
	return mem;
}


void BufferArray::Block::operator delete(void * mem)
{
	char * cmem = static_cast<char *>(mem);
	delete [] cmem;
}


void BufferArray::Block::operator delete(void * mem, size_t)
{
	operator delete(mem);
}


BufferArray::Block * BufferArray::Block::alloc(size_t len)
{
	Block * block = new (len) Block(len);
	return block;
}
	

}  // end namespace LLCore