nlib
DynamicAlignedStorage.h
Go to the documentation of this file.
1 
2 #pragma once
3 #ifndef INCLUDE_NN_NLIB_DYNAMICALIGNEDSTORAGE_H_
4 #define INCLUDE_NN_NLIB_DYNAMICALIGNEDSTORAGE_H_
5 
6 #include "nn/nlib/Config.h"
7 
8 NLIB_NAMESPACE_BEGIN
9 
11  public:
12  DynamicAlignedStorage() NLIB_NOEXCEPT : storage_(NULL) {}
13  NLIB_MOVE_MEMBER_HELPER_1(DynamicAlignedStorage, storage_)
14  errno_t Init(size_t size, size_t align) NLIB_NOEXCEPT {
15  if (align == 0) return EINVAL;
16  if ((align & (align - 1)) != 0) return EINVAL;
17 #ifdef NN_PLATFORM_CTR
18  void* p = nlib_malloc(size + align);
19 #elif defined(_MSC_VER)
20  void* p = _aligned_malloc(size, align);
21 #else
22  void* p = nlib_memalign(align, size);
23 #endif
24  if (!p) return ENOMEM;
25  storage_ = p;
26 #ifdef NN_PLATFORM_CTR
27  align_ = align;
28 #endif
29  return 0;
30  }
32  void* tmp = rhs.storage_;
33  rhs.storage_ = storage_;
34  storage_ = tmp;
35  }
37 #ifdef _MSC_VER
38  _aligned_free(storage_);
39 #else
40  nlib_free(storage_);
41 #endif
42  }
43  void* Get() NLIB_NOEXCEPT {
44 #ifndef NN_PLATFORM_CTR
45  return storage_;
46 #else
47  uintptr_t pos = (reinterpret_cast<uintptr_t>(storage_) + (align_ - 1)) & ~(align_ - 1);
48  return reinterpret_cast<void*>(pos);
49 #endif
50  }
51 
52  private:
53  void* storage_;
54 #ifdef NN_PLATFORM_CTR
55  size_t align_;
56 #endif
58 };
59 
62  lhs.swap(rhs);
63 }
64 
65 NLIB_NAMESPACE_END
66 
67 #endif // INCLUDE_NN_NLIB_DYNAMICALIGNEDSTORAGE_H_
#define NLIB_ALWAYS_INLINE
Indicates that the compiler is forced to perform inline expansion of functions.
Definition: Platform_unix.h:69
NLIB_CHECK_RESULT void * nlib_memalign(size_t alignment, size_t size)
A weak function that calls the C standard function memalign. nlib calls memalign via this function...
#define NLIB_DISALLOW_COPY_AND_ASSIGN(TypeName)
Prohibits use of the copy constructor and assignment operator for the class specified by TypeName...
Definition: Config.h:145
~DynamicAlignedStorage() noexcept
Destructor.
A class for obtaining aligned memory.
NLIB_CHECK_RESULT void * nlib_malloc(size_t size)
A weak function that calls the C standard function malloc. nlib calls malloc via this function...
void swap(DynamicAlignedStorage &rhs) noexcept
Swaps objects.
#define NLIB_NOEXCEPT
Defines noexcept geared to the environment, or the equivalent.
Definition: Config.h:86
void * Get() noexcept
Returns a pointer to the allocated region.
A file that contains the configuration information for each development environment.
DynamicAlignedStorage() noexcept
Instantiates the object with default parameters (default constructor).
void nlib_free(void *ptr)
A weak function that calls the C standard function free. nlib calls free via this function...
int errno_t
Indicates with an int-type typedef that a POSIX error value is returned as the return value...
Definition: NMalloc.h:24