Fix: update the correct pre-built script to cmake-sonar.sh
[ric-app/mc.git] / schemaparser / block_allocator.cc
1 // Distributed under the MIT license. Copyright (c) 2010, Ivan Vashchaev
2
3
4
5 #include <stdlib.h>
6 #include <algorithm>
7 #include "block_allocator.h"
8
9
10 namespace mc_json{
11
12 block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize)
13 {
14 }
15
16 block_allocator::~block_allocator()
17 {
18         while (m_head)
19         {
20                 block *temp = m_head->next;
21                 ::free(m_head);
22                 m_head = temp;
23         }
24 }
25
26 void block_allocator::swap(block_allocator &rhs)
27 {
28         std::swap(m_blocksize, rhs.m_blocksize);
29         std::swap(m_head, rhs.m_head);
30 }
31
32 void *block_allocator::malloc(size_t size)
33 {
34         if ((m_head && m_head->used + size > m_head->size) || !m_head)
35         {
36                 // calc needed size for allocation
37                 size_t alloc_size = std::max(sizeof(block) + size, m_blocksize);
38
39                 // create new block
40                 char *buffer = (char *)::malloc(alloc_size);
41                 block *b = reinterpret_cast<block *>(buffer);
42                 b->size = alloc_size;
43                 b->used = sizeof(block);
44                 b->buffer = buffer;
45                 b->next = m_head;
46                 m_head = b;
47         }
48
49         void *ptr = m_head->buffer + m_head->used;
50         m_head->used += size;
51         return ptr;
52 }
53
54 void block_allocator::free()
55 {
56         block_allocator(0).swap(*this);
57 }
58
59 }