Merge with MPC-HC 6d1472b2f18266d92e5bc068667de348c0cd3b3b.
[xy_vsfilter.git] / src / subtitles / xy_malloc.cpp
blob843ecb51ecabdbe41030e581ec1628f751eda211
1 /************************************************************************/
2 /* author: xy */
3 /* date: 20110514 */
4 /************************************************************************/
5 #include "xy_malloc.h"
6 #include <stdint.h>
7 #include <malloc.h>
8 #include <string.h>
10 //gathered from x264
11 /****************************************************************************
12 * xy_malloc:
13 ****************************************************************************/
14 void *xy_malloc( int i_size, int align_shift )
16 const int ALIGNMENT = 16;
17 const int MASK = ALIGNMENT - 1;
18 uint8_t * buf;
19 uint8_t * align_buf;
20 align_shift &= MASK;
21 buf = (uint8_t *) malloc( i_size + MASK + sizeof( void ** ) +
22 sizeof( int ) );
23 align_buf = buf + MASK + sizeof( void ** ) + sizeof( int );
24 align_buf -= (ALIGNMENT + ((intptr_t) align_buf & MASK) - align_shift) & MASK;
25 *( (void **) ( align_buf - sizeof( void ** ) ) ) = buf;
26 *( (int *) ( align_buf - sizeof( void ** ) - sizeof( int ) ) ) = i_size;
27 return align_buf;
30 /****************************************************************************
31 * xy_free:
32 ****************************************************************************/
33 void xy_free( void *p )
35 if( p )
37 free( *( ( ( void **) p ) - 1 ) );
41 /****************************************************************************
42 * xy_realloc:
43 ****************************************************************************/
44 void *xy_realloc( void *p, int i_size, int align_shift )
46 int i_old_size = 0;
47 uint8_t * p_new;
48 if( p )
50 i_old_size = *( (int*) ( (uint8_t*) p - sizeof( void ** ) -
51 sizeof( int ) ) );
53 p_new = (uint8_t*)xy_malloc( i_size, align_shift );
54 if( i_old_size > 0 && i_size > 0 )
56 memcpy( p_new, p, ( i_old_size < i_size ) ? i_old_size : i_size );
58 xy_free( p );
59 return p_new;