3/3 of old-style casting
[alexxy/gromacs.git] / src / gromacs / utility / allocator.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \file
36  * \brief
37  * Declares gmx::Allocator template whose allocation functionality is
38  * configured both by type of object allocated and a policy class that
39  * configures the necessary matching malloc and free operation.
40  *
41  * \author Erik Lindahl <erik.lindahl@gmail.com>
42  * \author Mark Abraham <mark.j.abraham@gmail.com>
43  * \inpublicapi
44  * \ingroup module_utility
45  */
46 #ifndef GMX_UTILITY_ALLOCATOR_H
47 #define GMX_UTILITY_ALLOCATOR_H
48
49 #include <cstddef>
50
51 #include <memory>
52 #include <new>
53
54 #include "gromacs/utility/basedefinitions.h"
55
56 namespace gmx
57 {
58
59 /*! \libinternal \brief Policy-based memory allocator.
60  *
61  *  \tparam T                 Type of objects to allocate
62  *  \tparam AllocationPolicy  Policy of (matching) allocation and deallocation functions.
63  *
64  * This class can be used for the optional allocator template
65  * parameter in standard library containers. It must be configured
66  * with both the type of object to allocate, and an AllocationPolicy
67  * which effectively wraps a matching pair of malloc and free
68  * functions. This permits implementing a family of related allocators
69  * e.g. with SIMD alignment, GPU host-side page locking, or perhaps
70  * both, in a way that preserves a common programming interface and
71  * duplicates minimal code.
72  *
73  * AllocationPolicy is used as a base class, so that if
74  * AllocationPolicy is stateless, then the empty base optimization
75  * will ensure that Allocation is also stateless, and objects made
76  * with the Allocator will incur no size penalty. (Embedding an
77  * AllocationPolicy object incurs a size penalty always, even if the
78  * object is empty.) Normally a stateless allocator will be used.
79  *
80  * However, an AllocationPolicy with state might be desirable for
81  * simplifying writing code that needs to allocate suitably for a
82  * transfer to a GPU. That code needs to specify an Allocator that can
83  * do the right job, which can be stateless. However, if we have code
84  * that will not know until run time whether a GPU transfer will
85  * occur, then the allocator needs to be aware of the state.  That
86  * will increase the size of a container that uses the stateful
87  * allocator.
88  *
89  * \throws std::bad_alloc Instead of a GROMACS exception object, we
90  * throw the standard one on allocation failures to make it as
91  * compatible as possible with the errors expected by code using the
92  * standard library containers.
93  *
94  * \inlibraryapi
95  * \ingroup module_utility
96  */
97 template <class T, typename AllocationPolicy>
98 class Allocator : public AllocationPolicy
99 {
100     public:
101         // The standard library specification for a custom allocator
102         // requires these typedefs, with this capitalization/underscoring.
103         typedef T              value_type;      //!< Type of allocated elements
104         typedef T             &reference;       //!< Reference to allocated elements
105         typedef const T       &const_reference; //!< Constant reference to allocated elements
106         typedef T *            pointer;         //!< Pointer to allocated elements
107         typedef const T *      const_pointer;   //!< Constant pointer to allocated elements
108         typedef std::size_t    size_type;       //!< Integer type to use for size of objects
109         typedef std::ptrdiff_t difference_type; //!< Type to hold differences between pointers
110
111         // This typedef is required by GROMACS for testing and assertions
112         typedef AllocationPolicy allocation_policy; //!< Type of the AllocationPolicy
113
114         /*! \libinternal \brief Standard-required typedef to use allocator with different class.
115          *
116          *  \tparam U new class
117          *
118          *  This is used for things like std::list where the size of each link
119          *  is larger than the class stored in the link.
120          *
121          *  Required by the specification for an allocator.
122          */
123         template <class U>
124         struct rebind
125         {
126             typedef Allocator<U, AllocationPolicy> other; //!< Align class U with our alignment
127         };
128
129         /*! \brief Templated copy constructor
130          *
131          * This template constructor cannot be auto-generated, and is
132          * normally unused, except e.g. MSVC2015 standard library uses
133          * it in debug mode, presumably to implement some checks.
134          */
135         template <class U>
136         explicit Allocator(const Allocator<U, AllocationPolicy> & /*unused*/) {}
137
138         /*! \brief Constructor
139          *
140          * No constructor can be auto-generated in the presence of any
141          * user-defined constructor, but we want the default constructor.
142          */
143         Allocator() = default;
144
145         /*! \brief Constructor to accept an AllocationPolicy.
146          *
147          * This is useful for AllocationPolicies with state.
148          */
149         Allocator(const AllocationPolicy &p) : AllocationPolicy(p) {}
150
151         /*! \brief Return address of an object
152          *
153          *  \param r Reference to object of type T
154          *  \return Pointer to T memory
155          */
156         pointer
157         address(reference r) const { return &r; }
158
159         /*! \brief Return address of a const object
160          *
161          *  \param r Const reference to object of type T
162          *  \return Pointer to T memory
163          */
164         const_pointer
165         address(const_reference r) const { return &r; }
166
167         /*! \brief Do the actual memory allocation
168          *
169          *  \param n    Number of elements of type T to allocate. n can be
170          *              0 bytes, which will return a non-null properly aligned
171          *              and padded pointer that should not be used.
172          *  \param hint Optional value returned from previous call to allocate.
173          *              For now this is not used.
174          *  \return Pointer to allocated memory
175          *
176          *  \throws std::bad_alloc if the allocation fails.
177          */
178         pointer
179         allocate(std::size_t n, typename std::allocator<void>::const_pointer gmx_unused hint = nullptr)
180         {
181             void *p = AllocationPolicy::malloc(n*sizeof(T));
182
183             if (p == nullptr)
184             {
185                 throw std::bad_alloc();
186             }
187             else
188             {
189                 return static_cast<pointer>(p);
190             }
191         }
192
193         /*! \brief Release memory
194          *
195          * \param p  Pointer to previously allocated memory returned from allocate()
196          * \param n  number of objects previously passed to allocate()
197          */
198         void
199         deallocate(pointer p, std::size_t gmx_unused n)
200         {
201             AllocationPolicy::free(p);
202         }
203
204         //! Return the policy object for this allocator.
205         AllocationPolicy getPolicy() const
206         {
207             return *this;
208         }
209
210         /*! \brief Construct an object without allocating memory
211          *
212          * \tparam Args  Variable-length list of types for constructor args
213          * \param p      Adress of memory where to construct object
214          * \param args   Variable-length list of arguments to constructor
215          */
216         template<class ... Args>
217         void
218         construct(pointer p, Args && ... args) { ::new(p)T(std::forward<Args>(args) ...); }
219
220         /*! \brief Call the destructor of object without releasing memory
221          *
222          * \param p  Address of memory where to destroy object
223          */
224         void
225         destroy(pointer p) { p->~value_type(); }
226
227         /*! \brief Return largest number of objects that can be allocated
228          *
229          * This will be set such that the number of objects T multiplied by
230          * the size of each object is the largest value that can be represented
231          * by size_type.
232          */
233         std::size_t
234         max_size() const { return (static_cast<std::size_t>(0) - static_cast<std::size_t>(1)) / sizeof(T); }
235
236         /*! \brief Return true if two allocators are identical
237          *
238          * This is a member function of the left-hand-side allocator.
239          */
240         template<class T2>
241         bool
242         operator==(const Allocator<T2, AllocationPolicy> & /*unused*/) const { return std::is_same<T, T2>::value; }
243
244         /*! \brief Return true if two allocators are different
245          *
246          * \param rhs Other allocator.
247          *
248          * This is a member function of the left-hand-side allocator.
249          */
250         bool
251         operator!=(const Allocator &rhs) const { return !operator==(rhs); }
252 };
253
254 }      // namespace gmx
255
256 #endif