namespace Cryville.Common.Buffers {
///
/// A resource pool that allows reusing instances of type .
///
/// The type of the objects in the pool.
public abstract class ObjectPool where T : class {
int _index;
readonly T[] _objs;
///
/// Creates an instance of the class.
///
/// The capacity of the pool.
public ObjectPool(int capacity) {
_objs = new T[capacity];
}
///
/// Rents a object from the pool.
///
/// The rented object.
public T Rent() {
T obj = null;
if (_index < _objs.Length) {
obj = _objs[_index];
_objs[_index++] = null;
}
if (obj == null) obj = Construct();
return obj;
}
///
/// Returns a rented object to the pool.
///
/// The object to return.
public void Return(T obj) {
if (_index > 0) _objs[--_index] = obj;
}
///
/// Constructs a new instance of type .
///
/// The new instance.
protected abstract T Construct();
}
}