TPIE

v1.1rc1-6-g0c97303
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 namespace tpie {
24 
25 namespace pipelining {
26 
27 namespace parallel_bits {
28 
40 template <typename T, size_t Align>
42  // Compute the size of an item with alignment padding (round up to nearest
43  // multiple of Align).
44  static const size_t aligned_size = (sizeof(T)+Align-1)/Align*Align;
45 
46  uint8_t * m_data;
47  size_t m_size;
48 
49  void dealloc() {
50  delete[] m_data;
51  m_size = 0;
52  }
53 
54 public:
55  aligned_array() : m_data(0), m_size(0) {}
56 
57  ~aligned_array() { realloc(0); }
58 
59  T * get(size_t idx) {
60  const size_t addr = (size_t) m_data;
61 
62  // Find the aligned base of the array by rounding the pointer up to the
63  // nearest multiple of Align.
64  const size_t alignedBase = (addr + Align - 1)/Align*Align;
65 
66  // Find the address of the element.
67  const size_t elmAddress = alignedBase + aligned_size * idx;
68 
69  return (T *) elmAddress;
70  }
71 
72  void realloc(size_t elms) {
73  dealloc();
74  m_size = elms;
75  // The buffer we get is not guaranteed to be aligned to any boundary.
76  // Request Align extra bytes to ensure we can find an aligned buffer of
77  // size aligned_size*elms.
78  m_data = m_size ? new uint8_t[aligned_size * elms + Align] : 0;
79  }
80 
81  size_t size() const { return m_size; }
82 };
83 
84 } // namespace parallel_bits
85 
86 } // namespace pipelining
87 
88 } // namespace tpie
89 
90 #endif // __TPIE_PIPELINING_PARALLEL_ALIGNED_ARRAY_H__
Aligned, uninitialized storage.
Definition: aligned_array.h:41