[Assorted-commits] SF.net SVN: assorted:[1008] cpp-commons/trunk/src/commons
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-10-08 22:05:17
|
Revision: 1008 http://assorted.svn.sourceforge.net/assorted/?rev=1008&view=rev Author: yangzhang Date: 2008-10-08 22:05:15 +0000 (Wed, 08 Oct 2008) Log Message: ----------- added: pool, array Added Paths: ----------- cpp-commons/trunk/src/commons/array.h cpp-commons/trunk/src/commons/pool.h Added: cpp-commons/trunk/src/commons/array.h =================================================================== --- cpp-commons/trunk/src/commons/array.h (rev 0) +++ cpp-commons/trunk/src/commons/array.h 2008-10-08 22:05:15 UTC (rev 1008) @@ -0,0 +1,33 @@ +#ifndef COMMONS_ARRAY_H +#define COMMONS_ARRAY_H + +#include <boost/scoped_array.hpp> + +namespace commons { + + using namespace boost; + + /** + * A thin wrapper around arrays. Like a fixed-size vector. Unlike array + * since the size can be dynamically determined. + */ + template<typename T> + class array : public scoped_array<T> { + public: + explicit array(size_t n) : scoped_array<T>(new T[n]), n_(n) {} + size_t size() { return n_; } + private: + size_t n_; + }; + + //template<typename T> + // class array { + // public: + // explicit array(int n) : a(new T[n]) {} + // private: + // scoped_array<T> a; + // }; + +} + +#endif Added: cpp-commons/trunk/src/commons/pool.h =================================================================== --- cpp-commons/trunk/src/commons/pool.h (rev 0) +++ cpp-commons/trunk/src/commons/pool.h 2008-10-08 22:05:15 UTC (rev 1008) @@ -0,0 +1,63 @@ +#ifndef COMMONS_POOL_H +#define COMMONS_POOL_H + +#include <boost/circular_buffer.hpp> +#include <commons/array.h> + +namespace commons { + + using namespace boost; + + /** + * A fixed-size pool of resources. + */ + template<typename T> + class pool { + public: + /** + * Create a pool of size \p size. These resources are created and stored + * in an array. + * \param[in] size The number of elements to create. + */ + pool(int size) : xs(size), ps(size) { + for (size_t i = 0; i < xs.size(); i++) + ps.push_back(&xs[i]); + } + + /** + * Take an item from the pool. + * \throw exception The pool is empty. + */ + T *take() { + check(!ps.empty(), "taking from empty pool"); + T *p = ps[0]; + ps.pop_front(); + return p; + } + + /** + * Release an item back into the pool. This doesn't check that the pointer + * being released was one that was originally taken from this pool. + * \param[in] The pointer to release. + * \throw exception The pool is full. + */ + void drop(T *p) { + check(ps.size() < ps.max_size(), "dropping into full pool"); + ps.push_back(p); + } + + /** + * Get the number of (remaining) items in the pool. + */ + size_t size() { + return ps.size(); + } + + private: + array<T> xs; + circular_buffer<T*> ps; + }; + +} + +#endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |