nlib
StackHeap.h
[詳解]
1 
2 #pragma once
3 #ifndef INCLUDE_NN_NLIB_HEAP_STACKHEAP_H_
4 #define INCLUDE_NN_NLIB_HEAP_STACKHEAP_H_
5 
6 #include "nn/nlib/Config.h"
7 
8 #if defined(_MSC_VER) && defined(nx_heap_EXPORTS)
9 #undef NLIB_VIS_PUBLIC
10 #define NLIB_VIS_PUBLIC NLIB_WINEXPORT
11 #endif
12 
13 NLIB_NAMESPACE_BEGIN
14 namespace heap {
15 
17  public:
18  StackHeap() NLIB_NOEXCEPT : cur_(NULL), heap_option_(0), start_(NULL), end_(NULL) {}
19  errno_t Init(void* start, size_t size, uint32_t heap_option) NLIB_NOEXCEPT;
20  void FreeAll() NLIB_NOEXCEPT { cur_ = start_; }
21  errno_t ResizeTop(void* p, size_t from_size, size_t to_size) NLIB_NOEXCEPT;
22  errno_t Adjust(void** start, size_t* size) NLIB_NOEXCEPT;
23 
24  void* Alloc(size_t n, size_t algn) NLIB_NOEXCEPT {
25  if (n == 0) return NULL;
26  if (algn == 0 || 0 != (algn & (algn - 1))) return NULL;
27  uint8_t* ret = this->RoundUp(cur_, algn);
28  uint8_t* new_top = ret + n;
29  if (new_top > end_) return NULL;
30  cur_ = new_top;
31  return ret;
32  }
33  void* Alloc(size_t n) NLIB_NOEXCEPT { return this->Alloc(n, 8); }
34  errno_t Free(void* p) NLIB_NOEXCEPT {
35  uint8_t* ptr = reinterpret_cast<uint8_t*>(p);
36  if (ptr >= start_ && ptr < cur_) {
37  cur_ = ptr;
38  return 0;
39  } else {
40  return EFAULT;
41  }
42  }
43  void Dump() NLIB_NOEXCEPT;
44 
45  private:
46  static uint8_t* RoundUp(uint8_t* ptr, size_t algn) NLIB_NOEXCEPT {
47  // algn is power of 2.
48  intptr_t tmp = reinterpret_cast<intptr_t>(ptr);
49  return reinterpret_cast<uint8_t*>(tmp + (-tmp & (algn - 1)));
50  }
51  void ChangeHeapRange(void* start, void* end) NLIB_NOEXCEPT {
52  start_ = reinterpret_cast<uint8_t*>(start);
53  end_ = reinterpret_cast<uint8_t*>(end);
54  }
55 
56  private:
57  uint8_t* cur_;
58 
59  uint32_t heap_option_;
60  uint8_t* start_;
61  uint8_t* end_;
62 };
63 
64 } // namespace heap
65 NLIB_NAMESPACE_END
66 
67 #if defined(_MSC_VER) && defined(nx_heap_EXPORTS)
68 #undef NLIB_VIS_PUBLIC
69 #define NLIB_VIS_PUBLIC NLIB_WINIMPORT
70 #endif
71 
72 #endif // INCLUDE_NN_NLIB_HEAP_STACKHEAP_H_
スタックに積み上げるようにメモリを確保していくアロケータです。
Definition: StackHeap.h:16
void * Alloc(size_t n) noexcept
メモリブロックを確保します。
Definition: StackHeap.h:33
#define NLIB_VIS_PUBLIC
関数やクラス等のシンボルをライブラリの外部に公開します。
Definition: Platform_unix.h:61
void * Alloc(size_t n, size_t algn) noexcept
アライメントを指定してメモリブロックを確保します。
Definition: StackHeap.h:24
#define NLIB_NOEXCEPT
環境に合わせてnoexcept 又は同等の定義がされます。
Definition: Config.h:86
errno_t Free(void *p) noexcept
次のメモリ確保位置をp の位置まで戻します。
Definition: StackHeap.h:34
開発環境別の設定が書かれるファイルです。
#define NLIB_FINAL
利用可能であればfinalが定義されます。そうでない場合は空文字列です。
Definition: Config.h:211
void FreeAll() noexcept
メモリを全て解放し、ヒープを初期化直後の状態に戻します。
Definition: StackHeap.h:20
int errno_t
intのtypedefで、戻り値としてPOSIXのエラー値を返すことを示します。
Definition: NMalloc.h:24