Update path to xapp descriptor. Add schema parser library
[ric-app/mc.git] / schemaparser / block_allocator.cc
diff --git a/schemaparser/block_allocator.cc b/schemaparser/block_allocator.cc
new file mode 100644 (file)
index 0000000..270efaf
--- /dev/null
@@ -0,0 +1,59 @@
+// Distributed under the MIT license. Copyright (c) 2010, Ivan Vashchaev
+
+
+
+#include <stdlib.h>
+#include <algorithm>
+#include "block_allocator.h"
+
+
+namespace mc_json{
+
+block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize)
+{
+}
+
+block_allocator::~block_allocator()
+{
+       while (m_head)
+       {
+               block *temp = m_head->next;
+               ::free(m_head);
+               m_head = temp;
+       }
+}
+
+void block_allocator::swap(block_allocator &rhs)
+{
+       std::swap(m_blocksize, rhs.m_blocksize);
+       std::swap(m_head, rhs.m_head);
+}
+
+void *block_allocator::malloc(size_t size)
+{
+       if ((m_head && m_head->used + size > m_head->size) || !m_head)
+       {
+               // calc needed size for allocation
+               size_t alloc_size = std::max(sizeof(block) + size, m_blocksize);
+
+               // create new block
+               char *buffer = (char *)::malloc(alloc_size);
+               block *b = reinterpret_cast<block *>(buffer);
+               b->size = alloc_size;
+               b->used = sizeof(block);
+               b->buffer = buffer;
+               b->next = m_head;
+               m_head = b;
+       }
+
+       void *ptr = m_head->buffer + m_head->used;
+       m_head->used += size;
+       return ptr;
+}
+
+void block_allocator::free()
+{
+       block_allocator(0).swap(*this);
+}
+
+}