TPIE

11a2c2d
aligned_array.h
1 // -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
2 // vi:set ts=4 sts=4 sw=4 noet :
3 // Copyright 2013, The TPIE development team
4 //
5 // This file is part of TPIE.
6 //
7 // TPIE is free software: you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation, either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // TPIE is distributed in the hope that it will be useful, but WITHOUT ANY
13 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 // License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with TPIE. If not, see <http://www.gnu.org/licenses/>
19 
20 #ifndef __TPIE_PIPELINING_PARALLEL_ALIGNED_ARRAY_H__
21 #define __TPIE_PIPELINING_PARALLEL_ALIGNED_ARRAY_H__
22 
23 #include <tpie/types.h>
24 
25 namespace tpie::pipelining::parallel_bits {
26 
38 template <typename T, size_t Align>
40  // Compute the size of an item with alignment padding (round up to nearest
41  // multiple of Align).
42  static const size_t aligned_size = (sizeof(T)+Align-1)/Align*Align;
43 
44  uint8_t * m_data;
45  size_t m_size;
46 
47  void dealloc() {
48  delete[] m_data;
49  m_size = 0;
50  }
51 
52 public:
53  aligned_array() : m_data(0), m_size(0) {}
54 
55  ~aligned_array() { realloc(0); }
56 
57  T * get(size_t idx) {
58  const size_t addr = (size_t) m_data;
59 
60  // Find the aligned base of the array by rounding the pointer up to the
61  // nearest multiple of Align.
62  const size_t alignedBase = (addr + Align - 1)/Align*Align;
63 
64  // Find the address of the element.
65  const size_t elmAddress = alignedBase + aligned_size * idx;
66 
67  return (T *) elmAddress;
68  }
69 
70  void realloc(size_t elms) {
71  dealloc();
72  m_size = elms;
73  // The buffer we get is not guaranteed to be aligned to any boundary.
74  // Request Align extra bytes to ensure we can find an aligned buffer of
75  // size aligned_size*elms.
76  m_data = m_size ? new uint8_t[aligned_size * elms + Align] : 0;
77  }
78 
79  size_t size() const { return m_size; }
80 };
81 
82 } // namespace tpie::pipelining::parallel_bits
83 
84 #endif // __TPIE_PIPELINING_PARALLEL_ALIGNED_ARRAY_H__
types.h
tpie::pipelining::parallel_bits::aligned_array
Aligned, uninitialized storage.
Definition: aligned_array.h:39