Add Windows support to portability/Memory.h
[folly.git] / folly / portability / Memory.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/portability/Memory.h>
18
19 #include <folly/portability/Config.h>
20
21 namespace folly {
22 namespace detail {
23 #if _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || \
24     (defined(__ANDROID__) && (__ANDROID_API__ > 15))
25 #include <errno.h>
26
27 // Use posix_memalign, but mimic the behaviour of memalign
28 void* aligned_malloc(size_t size, size_t align) {
29   void* ptr = nullptr;
30   int rc = posix_memalign(&ptr, align, size);
31   if (rc == 0) {
32     return ptr;
33   }
34   errno = rc;
35   return nullptr;
36 }
37
38 void aligned_free(void* aligned_ptr) {
39   free(aligned_ptr);
40 }
41 #elif defined(_WIN32)
42 #include <malloc.h> // nolint
43
44 void* aligned_malloc(size_t size, size_t align) {
45   return _aligned_malloc(size, alignment);
46 }
47
48 void aligned_free(void* aligned_ptr) {
49   _aligned_free(aligned_ptr);
50 }
51 #else
52 #include <malloc.h> // nolint
53
54 void* aligned_malloc(size_t size, size_t align) {
55   return memalign(align, size);
56 }
57
58 void aligned_free(void* aligned_ptr) {
59   free(aligned_ptr);
60 }
61 #endif
62 }
63 }