IndexPool.kl

Types

IndexPool (struct)

The IndexPool is an helper class for the management of array data, where free indices can be reused (re-allocated). For performance applications, using contiguous (array) storage of multiple elements improves speed by both minimizing heap allocation calls and by making a better use of CPU memory cache. This class helps to write such custom allocators.

注釈

IndexPool only helps to allocate/reuse data cells (indices), however it doesn’t hold the stored data per say (would need C++ -like templates to do that).

/*
** Example: IndexPool
*/

require Math, Containers;

struct Mat44Allocator {
  Mat44 matrices[];
  IndexPool indexPool;
};

inline UInt32 Mat44Allocator.allocate!() {
  UInt32 index;
  if( this.indexPool.getFreeIndex(index) )
    this.matrices.resize( this.indexPool.getIndexEnd() );
  return index;
}

inline Mat44Allocator.free!( UInt32 index ) {
  this.indexPool.unusedIndex(index);
}

operator entry(){

  Mat44Allocator mat44s;

  UInt32 first = mat44s.allocate();
  mat44s.matrices[first].setTranslation( Vec3(1,0,0) );

  UInt32 second = mat44s.allocate();
  mat44s.matrices[second].setTranslation( Vec3(2,0,0) );

  //Free the 1st allocated one, we no longer need it
  mat44s.free(first);

  report( mat44s.indexPool.getNumUsed() + " used out of " + mat44s.indexPool.getIndexEnd() );

  //Allocate a 3rd one, which should reuse the free 1st entry
  UInt32 third = mat44s.allocate();
  mat44s.matrices[third].setTranslation( Vec3(3,0,0) );

  report( mat44s.indexPool.getNumUsed() + " used out of " + mat44s.indexPool.getIndexEnd() );
}

/*
** Output:

1 used out of 2
2 used out of 2

*/

Methods

  IndexPool ( in IndexPool other )
  IndexPool ()
Boolean allAllocated ? ()
Boolean allFree ? ()
IndexPool clone ? ()
Boolean getFreeIndex ! ( out UInt32 index )
UInt32 getIndexEnd ? ()
Size getNumUsed ? ()
  reset ! ()
  setAllAsUnused ! ( in Boolean entry0IsReserved )
  unusedIndex ! ( in UInt32 index )