FlashGraph-ng
A new frontier in large-scale graph analysis and data mining
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Pages
aligned_allocator.h
1 #ifndef __ALIGNED_ALLOCATOR_H__
2 #define __ALIGNED_ALLOCATOR_H__
3 
4 /*
5  * Copyright 2014 Open Connectome Project (http://openconnecto.me)
6  * Written by Da Zheng (zhengda1936@gmail.com)
7  *
8  * This file is part of SAFSlib.
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  */
22 
23 #include <malloc.h>
24 
25 #include "common.h"
26 
27 /*
28  * The class can allocate aligned memory if the alignment provided
29  * by the user is a power of two.
30  */
31 class aligned_allocator
32 {
33  size_t alignment;
34 public:
35  aligned_allocator(size_t alignment) {
36  this->alignment = alignment;
37  bool aligned = align_check(alignment);
38  printf("aligned allocator: alignment: %ld, aligned: %d\n",
39  this->alignment, aligned);
40  // If we find it's not a power of 2, indicate it's not aligned.
41  if (!aligned)
42  this->alignment = 0;
43  }
44 
45  void *alloc(size_t size) {
46  if (alignment) {
47  void *buf = NULL;
48  int ret = posix_memalign(&buf, alignment, size);
49  if (ret == 0)
50  return buf;
51  else
52  return NULL;
53  }
54  else
55  return malloc(size);
56  }
57 
58  void dealloc(void *p) {
59  free(p);
60  }
61 };
62 
63 #endif