This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Aligned Block Allocation
  Submitted by



In MSVC 6.0 SP4 MS introduced the processor pack. This allowed use of MMX, 3DNow, SSE & SSE2 intrinsics via standard 'C'. While the intrinsics them self are not that interesting, the _aligned_malloc and __aligned_free are. This COTD is an STL like allocator that uses these new malloc & free functions. As a bonus, I added T_BLOCKSIZE to add extra padding at the end of the vector. This allows complete reg (mmreg/xmmreg) loads & stores without the worry of overwriting array bounds.

Download Associated File: blockalloc.txt (2,099 bytes)

//COTD Entry by James Johnson [kmeson@telocity.com]
///////////////////////////////////////////////////////////////////////////////
// Class:           aligned_BlockAlloc
// Base Classes:    std::allocator<T>
// Type:            template class
// Inheritance:     public
// Desc:            implements a block aligned allocator. Allocation occurs on
//                  T_ALIGNMENT boundary. This boundary must be a power of 2.
//                  The minimum block size allocated is T_BLOCKSIZE and must be
//                  non-ZERO. Allocations smaller than	T_BLOCKSIZE are rounded
//                  up to the nears multiple of T_BLOCKSIZE.
//
//                  Default alignment is 16 bytes
//                  Default block size is 8 bytes
//
// Usage:
//
//    std::vector<float,aligned_BlockAlloc<float> >	vecFloatAlign16by8;
//    vecFloatAlign16by8.resize(1024,1.0f)
//
///////////////////////////////////////////////////////////////////////////////
template <typename T,
           unsigned long T_ALIGNMENT=16,
           unsigned long T_BLOCKSIZE=8>
class aligned_BlockAlloc : public std::allocator<T>
{
private:
     typedef std::allocator<T>  BASE_TYPE;

public: aligned_BlockAlloc() {} aligned_BlockAlloc& operator=(const aligned_Alloc &r){ BASE_TYPE::operator=(r); return *this; }

pointer allocate(size_type n, const void *hint){ pointer p = NULL; unsigned long byteCount = sizeof(T) * n; unsigned long byteCountLeft = byteCount % T_BLOCKSIZE; if(byteCountLeft){ byteCount += T_BLOCKSIZE - byteCountLeft; } if(!hint){ p = reinterpret_cast<pointer>(_aligned_malloc(byteCount,T_ALIGNMENT)); }else{ p = reinterpret_cast<pointer>(_aligned_realloc((void*)hint,byteCount,T_ALIGNMENT)); } return p; }

void deallocate(pointer p, size_type n){ _aligned_free(p); }

void construct(pointer p, const T &val){ new(p) T(val); }

void destroy(pointer p){ p->~T(); } };

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.