TPIE

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