Simplify Allocator
[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 this typedef, with this capitalization/underscoring.
103         typedef T              value_type;      //!< Type of allocated elements
104
105         /*! \brief Constructor
106          *
107          * No constructor can be auto-generated in the presence of any
108          * user-defined constructor, but we want the default constructor.
109          */
110         Allocator() = default;
111
112         /*! \brief Constructor to accept an AllocationPolicy.
113          *
114          * This is useful for AllocationPolicies with state.
115          */
116         Allocator(const AllocationPolicy &p) : AllocationPolicy(p) {}
117
118         /*! \brief Do the actual memory allocation
119          *
120          *  \param n    Number of elements of type T to allocate. n can be
121          *              0 bytes, which will return a non-null properly aligned
122          *              and padded pointer that should not be used.
123          *  \param hint Optional value returned from previous call to allocate.
124          *              For now this is not used.
125          *  \return Pointer to allocated memory
126          *
127          *  \throws std::bad_alloc if the allocation fails.
128          */
129         value_type*
130         allocate(std::size_t n, typename std::allocator<void>::const_pointer gmx_unused hint = nullptr)
131         {
132             void *p = AllocationPolicy::malloc(n*sizeof(T));
133
134             if (p == nullptr)
135             {
136                 throw std::bad_alloc();
137             }
138             else
139             {
140                 return static_cast<value_type*>(p);
141             }
142         }
143
144         /*! \brief Release memory
145          *
146          * \param p  Pointer to previously allocated memory returned from allocate()
147          * \param n  number of objects previously passed to allocate()
148          */
149         void
150         deallocate(value_type* p, std::size_t gmx_unused n)
151         {
152             AllocationPolicy::free(p);
153         }
154
155         /*! \brief Return true if two allocators are identical
156          *
157          * This is a member function of the left-hand-side allocator.
158          * Always true for stateless polcies. Has to be defined in the policy for stateful policies.
159          * FUTURE: Can be removed with C++17 (is_always_equal)
160          */
161         template<class T2, class A = AllocationPolicy,
162                  typename          = typename std::enable_if<std::is_empty<A>::value>::type>
163         bool operator==(const Allocator<T2, AllocationPolicy> & /*unused*/) const { return true; }
164
165         /*! \brief Return true if two allocators are different
166          *
167          * \param rhs Other allocator.
168          *
169          * This is a member function of the left-hand-side allocator.
170          */
171         template<class T2>
172         bool operator!=(const Allocator<T2, AllocationPolicy> &rhs) const { return !(*this == rhs); }
173 };
174
175 }      // namespace gmx
176
177 #endif