Apply clang-format to source tree
[alexxy/gromacs.git] / src / gromacs / utility / arrayref.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, 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::ArrayRef
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \author Mark Abraham <mark.j.abraham@gmail.com>
41  * \author Roland Schulz <roland.schulz@intel.com>
42  * \author Berk Hess <hess@kth.se>
43  * \inpublicapi
44  * \ingroup module_utility
45  */
46 #ifndef GMX_UTILITY_ARRAYREF_H
47 #define GMX_UTILITY_ARRAYREF_H
48
49 #include <cstddef>
50
51 #include <array>
52 #include <iterator>
53 #include <stdexcept>
54 #include <utility>
55 #include <vector>
56
57 #include "gromacs/utility/gmxassert.h"
58
59 namespace gmx
60 {
61
62 /*! \brief STL-like interface to a C array of T (or part
63  * of a std container of T).
64  *
65  * \tparam T  Value type of elements.
66  *
67  * This class provides an interface similar to \c std::vector<T, A>, with the
68  * following main differences:
69  *  - This class does not have its own storage.  Instead, it references an
70  *    existing array of values (either a C-style array or part of an existing
71  *    std::vector<T, A> or std::array<T>).
72  *  - It is only possible to modify the values themselves through ArrayRef;
73  *    it is not possible to add or remove values.
74  *  - Copying objects of this type is cheap, and the copies behave identically
75  *    to the original object: the copy references the same set of values.
76  *
77  * This class is useful for writing wrappers that expose a view of the
78  * internal data stored as a single vector/array, which can be a whole
79  * or part of the underlying storage.
80  *
81  * Methods in this class do not throw, except where indicated.
82  *
83  * Note that due to a Doxygen limitation, the constructor that takes a C array
84  * whose size is known at compile time does not appear in the documentation.
85  *
86  * To refer to const data of type T, ArrayRef<const T> is used. For both const
87  * and non-const std::vector and std::array an ArrayRef view can be created.
88  * Attempting to create a non-const ArrayRef of a const vector/array will result
89  * in a compiler error in the respective constructor.
90  *
91  * For SIMD types there is template specialization available
92  * (e.g. ArrayRef<SimdReal>) in gromacs/simd/simd_memory.h which should have
93  * the same functionality as much as possible.
94  *
95  * \todo
96  * This class is not complete. There are likely also methods missing (not
97  * required for current usage).
98  *
99  * \inpublicapi
100  * \ingroup module_utility
101  */
102 template<typename T>
103 class ArrayRef
104 {
105 public:
106     //! Type of values stored in the reference.
107     typedef T value_type;
108     //! Type for representing size of the reference.
109     typedef size_t size_type;
110     //! Type for representing difference between two indices.
111     typedef ptrdiff_t difference_type;
112     //! Const reference to an element.
113     typedef const T& const_reference;
114     //! Const pointer to an element.
115     typedef const T* const_pointer;
116     //! Const iterator type to an element.
117     typedef const T* const_iterator;
118     //! Reference to an element.
119     typedef T& reference;
120     //! Pointer to an element.
121     typedef T* pointer;
122     //! Iterator type to an element.
123     typedef T* iterator;
124     //! Standard reverse iterator.
125     typedef std::reverse_iterator<iterator> reverse_iterator;
126     //! Standard reverse iterator.
127     typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
128
129     /*! \brief
130      * Constructs an empty reference.
131      */
132     ArrayRef() : begin_(nullptr), end_(nullptr) {}
133     /*! \brief
134      * Constructs a reference to a container or reference
135      *
136      * \param[in] o container to reference.
137      *
138      * Can be used to create a reference to a whole vector, std::array or
139      * an ArrayRef. The destination has to have a convertible pointer type
140      * (identical besides const or base class).
141      *
142      * Passed container must remain valid and not be reallocated for the
143      * lifetime of this object.
144      *
145      * This constructor is not explicit to allow directly passing
146      * a container to a method that takes ArrayRef.
147      */
148     template<typename U, typename = std::enable_if_t<std::is_convertible<typename std::remove_reference_t<U>::pointer, pointer>::value>>
149     ArrayRef(U&& o) : begin_(o.data()), end_(o.data() + o.size())
150     {
151     }
152     /*! \brief
153      * Constructs a reference to a particular range.
154      *
155      * \param[in] begin  Pointer to the beginning of a range.
156      * \param[in] end    Pointer to the end of a range.
157      *
158      * Passed pointers must remain valid for the lifetime of this object.
159      */
160     ArrayRef(pointer begin, pointer end) : begin_(begin), end_(end)
161     {
162         GMX_ASSERT(end >= begin, "Invalid range");
163     }
164     //! \cond
165     // Doxygen 1.8.5 doesn't parse the declaration correctly...
166     /*! \brief
167      * Constructs a reference to a C array.
168      *
169      * \param[in] array  C array to reference.
170      * \tparam    count  Deduced number of elements in \p array.
171      *
172      * This constructor can only be used with a real array (not with a
173      * pointer).  It constructs a reference to the whole array, without
174      * a need to pass the number of elements explicitly.  The compiler
175      * must be able to deduce the array size.
176      *
177      * Passed array must remain valid for the lifetime of this object.
178      *
179      * This constructor is not explicit to allow directly passing
180      * a C array to a function that takes an ArrayRef parameter.
181      */
182     template<size_t count>
183     ArrayRef(value_type (&array)[count]) : begin_(array), end_(array + count)
184     {
185     }
186     //! \endcond
187
188     //! Returns a reference to part of the memory.
189     ArrayRef subArray(size_type start, size_type count) const
190     {
191         return { begin_ + start, begin_ + start + count };
192     }
193     //! Returns an iterator to the beginning of the reference.
194     iterator begin() const { return begin_; }
195     //! Returns an iterator to the end of the reference.
196     iterator end() const { return end_; }
197     //! Returns an iterator to the reverse beginning of the reference.
198     reverse_iterator rbegin() const { return reverse_iterator(end()); }
199     //! Returns an iterator to the reverse end of the reference.
200     reverse_iterator rend() const { return reverse_iterator(begin()); }
201
202     /*! \brief Returns the size of the reference.
203      *
204      * \note Use ssize for any expression involving arithmetic operations
205          (including loop indices).
206      */
207     size_type size() const { return end_ - begin_; }
208     //! Returns the signed size of the reference.
209     index ssize() const { return size(); }
210     //! Identical to size().
211     size_type capacity() const { return end_ - begin_; }
212     //! Whether the reference refers to no memory.
213     bool empty() const { return begin_ == end_; }
214
215     //! Access an element.
216     reference operator[](size_type n) const { return begin_[n]; }
217     //! Access an element (throws on out-of-range error).
218     reference at(size_type n) const
219     {
220         if (n >= size())
221         {
222             throw std::out_of_range("Vector index out of range");
223         }
224         return begin_[n];
225     }
226     //! Returns the first element.
227     reference front() const { return *begin_; }
228     //! Returns the first element.
229     reference back() const { return *(end_ - 1); }
230
231     //! Returns a raw pointer to the contents of the array.
232     pointer data() const { return begin_; }
233
234     /*! \brief
235      * Swaps referenced memory with the other object.
236      *
237      * The actual memory areas are not modified, only the references are
238      * swapped.
239      */
240     void swap(ArrayRef<T>& other)
241     {
242         std::swap(begin_, other.begin_);
243         std::swap(end_, other.end_);
244     }
245
246 private:
247     pointer begin_;
248     pointer end_;
249 };
250
251 //! \copydoc ArrayRef::fromArray()
252 //! \related ArrayRef
253 template<typename T>
254 ArrayRef<T> arrayRefFromArray(T* begin, size_t size)
255 {
256     return ArrayRef<T>(begin, begin + size);
257 }
258
259 //! \copydoc ArrayRef::fromArray()
260 //! \related ArrayRef
261 template<typename T>
262 ArrayRef<const T> constArrayRefFromArray(const T* begin, size_t size)
263 {
264     return ArrayRef<const T>(begin, begin + size);
265 }
266
267 /*! \brief
268  * Create ArrayRef from container with type deduction
269  *
270  * \see ArrayRef
271  */
272 template<typename T>
273 ArrayRef<std::conditional_t<std::is_const<T>::value, const typename T::value_type, typename T::value_type>>
274 makeArrayRef(T& c)
275 {
276     return c;
277 }
278
279 /*! \brief
280  * Create ArrayRef to const T from container with type deduction
281  *
282  * \see ArrayRef
283  */
284 template<typename T>
285 ArrayRef<const typename T::value_type> makeConstArrayRef(const T& c)
286 {
287     return c;
288 }
289
290 /*! \brief
291  * Simple swap method for ArrayRef objects.
292  *
293  * \see ArrayRef::swap()
294  *
295  * \ingroup module_utility
296  */
297 template<typename T>
298 void swap(ArrayRef<T>& a, ArrayRef<T>& b)
299 {
300     a.swap(b);
301 }
302
303 /*! \brief Return a vector that is a copy of an ArrayRef.
304  *
305  * This makes it convenient, clear, and performant (the compiler will
306  * either do RVO to elide the temporary, or invoke the move constructor
307  * taking the unnamed temporary) to write a declaration like
308  *
309  *   auto v = copyOf(arrayRef);
310  *
311  * \ingroup module_utility
312  */
313 template<typename T>
314 std::vector<T> copyOf(const ArrayRef<const T>& arrayRef)
315 {
316     return std::vector<T>(arrayRef.begin(), arrayRef.end());
317 }
318
319 } // namespace gmx
320
321 #endif