Fixed newline characters throughout the code
[com/gs-lite.git] / src / lib / gscpaux / block_allocator.cpp
1 // Distributed under the MIT license. Copyright (c) 2010, Ivan Vashchaev
2
3 #include <stdlib.h>
4 #include <algorithm>
5 #include "block_allocator.h"
6
7 block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize)
8 {
9 }
10
11 block_allocator::~block_allocator()
12 {
13         while (m_head)
14         {
15                 block *temp = m_head->next;
16                 ::free(m_head);
17                 m_head = temp;
18         }
19 }
20
21 void block_allocator::swap(block_allocator &rhs)
22 {
23         std::swap(m_blocksize, rhs.m_blocksize);
24         std::swap(m_head, rhs.m_head);
25 }
26
27 void *block_allocator::malloc(size_t size)
28 {
29         if ((m_head && m_head->used + size > m_head->size) || !m_head)
30         {
31                 // calc needed size for allocation
32                 size_t alloc_size = std::max(sizeof(block) + size, m_blocksize);
33
34                 // create new block
35                 char *buffer = (char *)::malloc(alloc_size);
36                 block *b = reinterpret_cast<block *>(buffer);
37                 b->size = alloc_size;
38                 b->used = sizeof(block);
39                 b->buffer = buffer;
40                 b->next = m_head;
41                 m_head = b;
42         }
43
44         void *ptr = m_head->buffer + m_head->used;
45         m_head->used += size;
46         return ptr;
47 }
48
49 void block_allocator::free()
50 {
51         block_allocator(0).swap(*this);
52 }