• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_MEMORY_ALIGNED_MEMORY_H_
6 #define BASE_MEMORY_ALIGNED_MEMORY_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <type_traits>
12 
13 #include "base/base_export.h"
14 #include "base/compiler_specific.h"
15 #include "build/build_config.h"
16 
17 #if defined(COMPILER_MSVC)
18 #include <malloc.h>
19 #else
20 #include <stdlib.h>
21 #endif
22 
23 // A runtime sized aligned allocation can be created:
24 //
25 //   float* my_array = static_cast<float*>(AlignedAlloc(size, alignment));
26 //
27 //   // ... later, to release the memory:
28 //   AlignedFree(my_array);
29 //
30 // Or using unique_ptr:
31 //
32 //   std::unique_ptr<float, AlignedFreeDeleter> my_array(
33 //       static_cast<float*>(AlignedAlloc(size, alignment)));
34 
35 namespace base {
36 
37 // This can be replaced with std::aligned_malloc when we have C++17.
38 BASE_EXPORT void* AlignedAlloc(size_t size, size_t alignment);
39 
AlignedFree(void * ptr)40 inline void AlignedFree(void* ptr) {
41 #if defined(COMPILER_MSVC)
42   _aligned_free(ptr);
43 #else
44   free(ptr);
45 #endif
46 }
47 
48 // Deleter for use with unique_ptr. E.g., use as
49 //   std::unique_ptr<Foo, base::AlignedFreeDeleter> foo;
50 struct AlignedFreeDeleter {
operatorAlignedFreeDeleter51   inline void operator()(void* ptr) const {
52     AlignedFree(ptr);
53   }
54 };
55 
56 }  // namespace base
57 
58 #endif  // BASE_MEMORY_ALIGNED_MEMORY_H_
59