libcruft-util/pool.hpp

68 lines
1.8 KiB
C++
Raw Normal View History

/*
2015-04-13 18:05:28 +10:00
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
2015-04-13 18:05:28 +10:00
* http://www.apache.org/licenses/LICENSE-2.0
*
2015-04-13 18:05:28 +10:00
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
2016-01-19 18:29:13 +11:00
* Copyright 2011-2016 Danny Robson <danny@nerdcruft.net>
*/
#ifndef __UTIL_POOL_HPP
#define __UTIL_POOL_HPP
#include "nocopy.hpp"
2014-12-31 19:07:25 +11:00
#include <cstdlib>
namespace util {
/// a simple pre-allocated pool for storage of PODs.
///
/// non-POD types can be stored, but there are no guarantees for calling
/// item destructors at pool destruction time.
2012-08-22 16:12:26 +10:00
template <typename T>
class pool : public nocopy {
protected:
union node {
2016-01-19 18:29:13 +11:00
node *_node;
char _data[sizeof (T)];
};
2016-01-19 18:29:13 +11:00
node *m_head; // root address of allocation
node *m_next; // next available entry in the linked list
const size_t m_capacity;
size_t m_size;
public:
2012-08-22 16:12:26 +10:00
pool (unsigned int _capacity);
~pool ();
2014-12-31 19:07:25 +11:00
// Data management
template <typename ...Args>
2012-08-22 16:12:26 +10:00
T* acquire (Args&... args);
2012-08-22 16:12:26 +10:00
void release (T *data);
2014-12-31 19:07:25 +11:00
size_t capacity (void) const;
size_t size (void) const;
2016-01-19 18:29:13 +11:00
bool empty (void) const;
2014-12-31 19:07:25 +11:00
// Indexing
size_t index (const T*) const;
T& operator[] (size_t idx);
const T& operator[] (size_t idx) const;
};
}
2012-08-22 16:12:26 +10:00
#include "pool.ipp"
#endif // __UTIL_POOL_HPP