|
|
1.1 root 1: //
2: // nono
3: // Copyright (C) 2024 nono project
4: // Licensed under nono-license.txt
5: //
6:
7: //
8: // アラインされた配列
9: //
10:
11: #pragma once
12:
13: #include <stdlib.h>
14:
15: template<typename T, std::size_t align>
16: class AlignedArray
17: {
18: public:
19: AlignedArray()
20: {
21: }
22:
23: explicit AlignedArray(std::size_t num_)
24: {
25: Alloc(num_);
26: }
27:
28: ~AlignedArray()
29: {
30: Reset();
31: }
32:
1.1.1.2 ! root 33: // コピーコンストラクタ
! 34: AlignedArray(const AlignedArray& src)
! 35: {
! 36: Reset(src.num);
! 37: if (ptr) {
! 38: memcpy(ptr, src.ptr, num * sizeof(T));
! 39: }
! 40: }
! 41: // コピー代入演算子
! 42: AlignedArray& operator=(const AlignedArray& src)
! 43: {
! 44: Reset(src.num);
! 45: if (ptr) {
! 46: memcpy(ptr, src.ptr, num * sizeof(T));
! 47: }
! 48: return *this;
! 49: }
! 50:
1.1 root 51: void Reset()
52: {
53: free(ptr);
54: ptr = NULL;
55: num = 0;
56: }
57:
58: bool Reset(std::size_t new_num)
59: {
60: if (new_num == num) {
61: return true;
62: }
63: Reset();
1.1.1.2 ! root 64: if (new_num == 0) {
! 65: return true;
! 66: }
1.1 root 67: return Alloc(new_num);
68: }
69:
70: T *get() const noexcept
71: {
72: return ptr;
73: }
74:
75: explicit operator bool() const noexcept
76: {
77: return (ptr != NULL);
78: }
79:
80: private:
81: bool Alloc(std::size_t new_num)
82: {
83: assert(ptr == NULL);
84:
85: void *tmp;
86: int r = posix_memalign(&tmp, align, new_num * sizeof(T));
87: if (__predict_false(r != 0)) {
88: return false;
89: }
90: ptr = reinterpret_cast<T*>(tmp);
91: num = new_num;
92: return true;
93: }
94:
95: T *ptr {};
96: std::size_t num {};
97: };
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.