| 1 | // |
|---|
| 2 | // MessagePack for C++ memory pool |
|---|
| 3 | // |
|---|
| 4 | // Copyright (C) 2008 FURUHASHI Sadayuki |
|---|
| 5 | // |
|---|
| 6 | // Licensed under the Apache License, Version 2.0 (the "License"); |
|---|
| 7 | // you may not use this file except in compliance with the License. |
|---|
| 8 | // You may obtain a copy of the License at |
|---|
| 9 | // |
|---|
| 10 | // http://www.apache.org/licenses/LICENSE-2.0 |
|---|
| 11 | // |
|---|
| 12 | // Unless required by applicable law or agreed to in writing, software |
|---|
| 13 | // distributed under the License is distributed on an "AS IS" BASIS, |
|---|
| 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|---|
| 15 | // See the License for the specific language governing permissions and |
|---|
| 16 | // limitations under the License. |
|---|
| 17 | // |
|---|
| 18 | #include "zone.hpp" |
|---|
| 19 | |
|---|
| 20 | namespace msgpack { |
|---|
| 21 | |
|---|
| 22 | |
|---|
| 23 | void* zone::alloc() |
|---|
| 24 | { |
|---|
| 25 | if(m_pool.size()*ZONE_CHUNK_SIZE <= m_used) { |
|---|
| 26 | cell_t* chunk = (cell_t*)malloc(sizeof(cell_t)*ZONE_CHUNK_SIZE); |
|---|
| 27 | if(!chunk) { throw std::bad_alloc(); } |
|---|
| 28 | try { |
|---|
| 29 | m_pool.push_back(chunk); |
|---|
| 30 | } catch (...) { |
|---|
| 31 | free(chunk); |
|---|
| 32 | throw; |
|---|
| 33 | } |
|---|
| 34 | } |
|---|
| 35 | void* data = m_pool[m_used/ZONE_CHUNK_SIZE][m_used%ZONE_CHUNK_SIZE].data; |
|---|
| 36 | ++m_used; |
|---|
| 37 | return data; |
|---|
| 38 | } |
|---|
| 39 | |
|---|
| 40 | void zone::clear() |
|---|
| 41 | { |
|---|
| 42 | if(!m_pool.empty()) { |
|---|
| 43 | for(size_t b=0; b < m_used/ZONE_CHUNK_SIZE; ++b) { |
|---|
| 44 | cell_t* c(m_pool[b]); |
|---|
| 45 | for(size_t e=0; e < ZONE_CHUNK_SIZE; ++e) { |
|---|
| 46 | reinterpret_cast<object_class*>(c[e].data)->~object_class(); |
|---|
| 47 | } |
|---|
| 48 | } |
|---|
| 49 | cell_t* c(m_pool.back()); |
|---|
| 50 | for(size_t e=0; e < m_used%ZONE_CHUNK_SIZE; ++e) { |
|---|
| 51 | reinterpret_cast<object_class*>(c[e].data)->~object_class(); |
|---|
| 52 | } |
|---|
| 53 | |
|---|
| 54 | for(pool_t::iterator it(m_pool.begin()), it_end(m_pool.end()); |
|---|
| 55 | it != it_end; |
|---|
| 56 | ++it) { |
|---|
| 57 | free(*it); |
|---|
| 58 | } |
|---|
| 59 | m_pool.clear(); |
|---|
| 60 | } |
|---|
| 61 | m_used = 0; |
|---|
| 62 | |
|---|
| 63 | for(user_finalizer_t::reverse_iterator it(m_user_finalizer.rbegin()), it_end(m_user_finalizer.rend()); |
|---|
| 64 | it != it_end; |
|---|
| 65 | ++it) { |
|---|
| 66 | it->call(); |
|---|
| 67 | } |
|---|
| 68 | m_user_finalizer.clear(); |
|---|
| 69 | } |
|---|
| 70 | |
|---|
| 71 | |
|---|
| 72 | } // namespace msgpack |
|---|
| 73 | |
|---|