Code to show

Marius Muja mariusm at cs.ubc.ca
Wed Mar 5 15:20:28 PST 2008


I'm using something very similar in my speed-critical code:


/**
  * Allocates (using C's malloc) a generic type T.
  *
  * Params:
  *     count = number of instances to allocate.
  * Returns: pointer (of type T*) to memory buffer
  */
public T* allocate(T)(int count = 1)
{
	T* mem = cast(T*) tango.stdc.stdlib.malloc(T.sizeof*count);
	return mem;
}

/**
  * Allocates (using C's malloc) a one dimensional array.
  * Params:
  *     count = array size
  * Returns: new array
  */
public T[] allocate(T : T[])(int count)
{
	T* mem = cast(T*) tango.stdc.stdlib.malloc(count*T.sizeof);		
	return mem[0..count];
}

/**
  * Allocates (using C's malloc) a two dimensional array.
  *
  * Params:
  *     rows = rows in the new array
  *     cols = cols in the new array, if cols==-1 then this function
  *     		allocates a one dimensional array of empty arrays
  * Returns: the new two dimensional array
  */
public T[][] allocate(T : T[][])(int rows, int cols = -1)
{
	if (cols == -1) {
		T[]* mem = cast(T[]*) tango.stdc.stdlib.malloc(rows*(T[]).sizeof);
		return mem[0..rows];
	}
	else {
		//if (rows & 1) rows++; // for 16 byte allignment	
		void* mem = 
tango.stdc.stdlib.malloc(rows*(T[]).sizeof+rows*cols*T.sizeof);
		T[]* index = cast(T[]*) mem;
		T* mat = cast(T*) (mem+rows*(T[]).sizeof);
		
		for (int i=0;i<rows;++i) {
			index[i] = mat[0..cols];
			mat += cols;
		}
		
		return index[0..rows];
	}
}

/**
  * Template to check is a type is an array.
  */
private template isArray(T)
{
     static if( is( T U : U[] ) )
         const isArray = true;
     else
         const isArray = false;
}

/**
  * Frees allocated memory.
  * Params:
  *     ptr = variable to free.
  */
public void free(T)(T ptr)
{
	static if ( isArray!(T) ) {
		tango.stdc.stdlib.free(cast(void*) ptr.ptr);
	}
	else {
		tango.stdc.stdlib.free(cast(void*) ptr);
	}
}


More information about the Digitalmars-d-learn mailing list