1 /*
2  * Copyright (c) 2014 Simon Symeonidis <lethaljellybean/at/gmail/com>
3  * Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
4  *
5  * This file is part of LMMS - https://lmms.io
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public
18  * License along with this program (see COPYING); if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  * Boston, MA 02110-1301 USA.
21  *
22  */
23 
24 #include <stdlib.h>
25 
26 #include "lmms_basics.h"
27 #include "MemoryHelper.h"
28 
29 /**
30  * Allocate a number of bytes and return them.
31  * @param byteNum is the number of bytes
32  */
alignedMalloc(size_t byteNum)33 void* MemoryHelper::alignedMalloc( size_t byteNum )
34 {
35 	char *ptr, *ptr2, *aligned_ptr;
36 	int align_mask = ALIGN_SIZE - 1;
37 
38 	ptr = static_cast<char*>( malloc( byteNum + ALIGN_SIZE + sizeof( int ) ) );
39 
40 	if( ptr == NULL ) return NULL;
41 
42 	ptr2 = ptr + sizeof( int );
43 	aligned_ptr = ptr2 + ( ALIGN_SIZE - ( ( size_t ) ptr2 & align_mask ) );
44 
45 	ptr2 = aligned_ptr - sizeof( int );
46 	*( ( int* ) ptr2 ) = ( int )( aligned_ptr - ptr );
47 
48 	return aligned_ptr;
49 }
50 
51 
52 /**
53  * Free an aligned buffer
54  * @param _buffer is the buffer to free
55  */
alignedFree(void * _buffer)56 void MemoryHelper::alignedFree( void* _buffer )
57 {
58 	if( _buffer )
59 	{
60 		int *ptr2 = static_cast<int*>( _buffer ) - 1;
61 		_buffer = static_cast<char*>( _buffer ) - *ptr2;
62 		free( _buffer );
63 	}
64 }
65 
66