Fix undefined behavior flagged by UBSAN
[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 by the GROMACS development team.
5  * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \file
37  * \brief
38  * Declares gmx::ArrayRef
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \author Mark Abraham <mark.j.abraham@gmail.com>
42  * \author Roland Schulz <roland.schulz@intel.com>
43  * \author Berk Hess <hess@kth.se>
44  * \inpublicapi
45  * \ingroup module_utility
46  */
47 #ifndef GMX_UTILITY_ARRAYREF_H
48 #define GMX_UTILITY_ARRAYREF_H
49
50 #include <cstddef>
51
52 #include <array>
53 #include <iterator>
54 #include <stdexcept>
55 #include <utility>
56 #include <vector>
57
58 #if __has_include(<boost/stl_interfaces/iterator_interface.hpp>)
59 #    include <boost/stl_interfaces/iterator_interface.hpp>
60 #else // fallback for installed headers
61 #    include <gromacs/external/boost/stl_interfaces/iterator_interface.hpp>
62 #endif
63
64 #include "gromacs/utility/gmxassert.h"
65
66 namespace gmx
67 {
68
69 template<class T>
70 struct ArrayRefIter :
71     boost::stl_interfaces::iterator_interface<ArrayRefIter<T>, std::random_access_iterator_tag, T>
72 {
73     // This default constructor does not initialize it_
74     constexpr ArrayRefIter() noexcept {}
75     constexpr explicit ArrayRefIter(T* it) noexcept : it_(it) {}
76     // TODO: Use std::is_const_v when CUDA 11 is a requirement.
77     template<class T2 = T, class = std::enable_if_t<std::is_const<T2>::value>>
78     constexpr ArrayRefIter(ArrayRefIter<std::remove_const_t<T2>> it) noexcept : it_(&*it)
79     {
80     }
81     constexpr T*            data() const noexcept { return it_; }
82     constexpr T&            operator*() const noexcept { return *it_; }
83     constexpr ArrayRefIter& operator+=(std::ptrdiff_t i) noexcept
84     {
85         it_ += i;
86         return *this;
87     }
88     constexpr auto operator-(ArrayRefIter other) const noexcept { return it_ - other.it_; }
89
90 private:
91     T* it_;
92 };
93
94 /*! \brief STL-like interface to a C array of T (or part
95  * of a std container of T).
96  *
97  * \tparam T  Value type of elements.
98  *
99  * This class provides an interface similar to \c std::vector<T, A>, with the
100  * following main differences:
101  *  - This class does not have its own storage.  Instead, it references an
102  *    existing array of values (either a C-style array or part of an existing
103  *    std::vector<T, A> or std::array<T>).
104  *  - It is only possible to modify the values themselves through ArrayRef;
105  *    it is not possible to add or remove values.
106  *  - Copying objects of this type is cheap, and the copies behave identically
107  *    to the original object: the copy references the same set of values.
108  *
109  * This class is useful for writing wrappers that expose a view of the
110  * internal data stored as a single vector/array, which can be a whole
111  * or part of the underlying storage.
112  *
113  * Methods in this class do not throw, except where indicated.
114  *
115  * Note that due to a Doxygen limitation, the constructor that takes a C array
116  * whose size is known at compile time does not appear in the documentation.
117  *
118  * To refer to const data of type T, ArrayRef<const T> is used. For both const
119  * and non-const std::vector and std::array an ArrayRef view can be created.
120  * Attempting to create a non-const ArrayRef of a const vector/array will result
121  * in a compiler error in the respective constructor.
122  *
123  * For SIMD types there is template specialization available
124  * (e.g. ArrayRef<SimdReal>) in gromacs/simd/simd_memory.h which should have
125  * the same functionality as much as possible.
126  *
127  * \todo
128  * This class is not complete. There are likely also methods missing (not
129  * required for current usage).
130  *
131  * \inpublicapi
132  * \ingroup module_utility
133  */
134 template<typename T>
135 class ArrayRef
136 {
137 public:
138     //! Type of values stored in the reference.
139     typedef T value_type;
140     //! Type for representing size of the reference.
141     typedef size_t size_type;
142     //! Type for representing difference between two indices.
143     typedef ptrdiff_t difference_type;
144     //! Const reference to an element.
145     typedef const T& const_reference;
146     //! Const pointer to an element.
147     typedef const T* const_pointer;
148     //! Const iterator type to an element.
149     typedef ArrayRefIter<const T> const_iterator;
150     //! Reference to an element.
151     typedef T& reference;
152     //! Pointer to an element.
153     typedef T* pointer;
154     //! Iterator type to an element.
155     typedef ArrayRefIter<T> iterator;
156     //! Standard reverse iterator.
157     typedef std::reverse_iterator<iterator> reverse_iterator;
158     //! Standard reverse iterator.
159     typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
160
161     /*! \brief
162      * Constructs an empty reference.
163      */
164     ArrayRef() : begin_(nullptr), end_(nullptr) {}
165     /*! \brief
166      * Constructs a reference to a container or reference
167      *
168      * \param[in] o container to reference.
169      *
170      * Can be used to create a reference to a whole vector, std::array or
171      * an ArrayRef. The destination has to have a convertible pointer type
172      * (identical besides const or base class).
173      *
174      * Passed container must remain valid and not be reallocated for the
175      * lifetime of this object.
176      *
177      * This constructor is not explicit to allow directly passing
178      * a container to a method that takes ArrayRef.
179      *
180      * \todo Use std::is_convertible_v when CUDA 11 is a requirement.
181      */
182     template<typename U, typename = std::enable_if_t<std::is_convertible<typename std::remove_reference_t<U>::pointer, pointer>::value>>
183     ArrayRef(U&& o) : begin_(o.data()), end_(o.data() + o.size())
184     {
185     }
186     /*! \brief
187      * Constructs a reference to a particular range.
188      *
189      * \param[in] begin  Pointer to the beginning of a range.
190      * \param[in] end    Pointer to the end of a range.
191      *
192      * Passed pointers must remain valid for the lifetime of this object.
193      */
194     ArrayRef(pointer begin, pointer end) : begin_(begin), end_(end)
195     {
196         GMX_ASSERT(end >= begin, "Invalid range");
197     }
198     /*! \brief
199      * Constructs a reference to a particular range.
200      *
201      * \param[in] begin  Iterator to the beginning of a range.
202      * \param[in] end    iterator to the end of a range.
203      *
204      * Passed iterators must remain valid for the lifetime of this object.
205      */
206     ArrayRef(iterator begin, iterator end) : begin_(begin), end_(end)
207     {
208         GMX_ASSERT(end >= begin, "Invalid range");
209     }
210     //! \cond
211     // Doxygen 1.8.5 doesn't parse the declaration correctly...
212     /*! \brief
213      * Constructs a reference to a C array.
214      *
215      * \param[in] array  C array to reference.
216      * \tparam    count  Deduced number of elements in \p array.
217      *
218      * This constructor can only be used with a real array (not with a
219      * pointer).  It constructs a reference to the whole array, without
220      * a need to pass the number of elements explicitly.  The compiler
221      * must be able to deduce the array size.
222      *
223      * Passed array must remain valid for the lifetime of this object.
224      *
225      * This constructor is not explicit to allow directly passing
226      * a C array to a function that takes an ArrayRef parameter.
227      */
228     template<size_t count>
229     ArrayRef(value_type (&array)[count]) : begin_(array), end_(array + count)
230     {
231     }
232     //! \endcond
233
234     //! Returns a reference to part of the memory.
235     ArrayRef subArray(size_type start, size_type count) const
236     {
237         return { begin_ + start, begin_ + start + count };
238     }
239     //! Returns an iterator to the beginning of the reference.
240     iterator begin() const { return iterator(begin_); }
241     //! Returns an iterator to the end of the reference.
242     iterator end() const { return iterator(end_); }
243     //! Returns an iterator to the reverse beginning of the reference.
244     reverse_iterator rbegin() const { return reverse_iterator(end()); }
245     //! Returns an iterator to the reverse end of the reference.
246     reverse_iterator rend() const { return reverse_iterator(begin()); }
247
248     /*! \brief Returns the size of the reference.
249      *
250      * \note Use ssize for any expression involving arithmetic operations
251          (including loop indices).
252      */
253     size_type size() const { return end_ - begin_; }
254     //! Returns the signed size of the reference.
255     index ssize() const { return size(); }
256     //! Identical to size().
257     size_type capacity() const { return end_ - begin_; }
258     //! Whether the reference refers to no memory.
259     bool empty() const { return begin_ == end_; }
260
261     //! Access an element.
262     reference operator[](size_type n) const { return begin_[n]; }
263     //! Access an element (throws on out-of-range error).
264     reference at(size_type n) const
265     {
266         if (n >= size())
267         {
268             throw std::out_of_range("Vector index out of range");
269         }
270         return begin_[n];
271     }
272     //! Returns the first element.
273     reference front() const { return *(begin_); }
274     //! Returns the first element.
275     reference back() const { return *(end_ - 1); }
276
277     //! Returns a raw pointer to the contents of the array.
278     pointer data() const { return begin_.data(); }
279
280     /*! \brief
281      * Swaps referenced memory with the other object.
282      *
283      * The actual memory areas are not modified, only the references are
284      * swapped.
285      */
286     void swap(ArrayRef<T>& other)
287     {
288         std::swap(begin_, other.begin_);
289         std::swap(end_, other.end_);
290     }
291
292 private:
293     iterator begin_;
294     iterator end_;
295 };
296
297 //! \copydoc ArrayRef::fromArray()
298 //! \related ArrayRef
299 template<typename T>
300 ArrayRef<T> arrayRefFromArray(T* begin, size_t size)
301 {
302     return ArrayRef<T>(begin, begin + size);
303 }
304
305 //! \copydoc ArrayRef::fromArray()
306 //! \related ArrayRef
307 template<typename T>
308 ArrayRef<const T> constArrayRefFromArray(const T* begin, size_t size)
309 {
310     return ArrayRef<const T>(begin, begin + size);
311 }
312
313 /*! \brief
314  * Create ArrayRef from container with type deduction
315  *
316  * \see ArrayRef
317  *
318  * \todo Use std::is_const_v when CUDA 11 is a requirement.
319  */
320 template<typename T>
321 ArrayRef<std::conditional_t<std::is_const<T>::value, const typename T::value_type, typename T::value_type>>
322 makeArrayRef(T& c)
323 {
324     return c;
325 }
326
327 /*! \brief
328  * Create ArrayRef to const T from container with type deduction
329  *
330  * \see ArrayRef
331  */
332 template<typename T>
333 ArrayRef<const typename T::value_type> makeConstArrayRef(const T& c)
334 {
335     return c;
336 }
337
338 /*! \brief
339  * Simple swap method for ArrayRef objects.
340  *
341  * \see ArrayRef::swap()
342  *
343  * \ingroup module_utility
344  */
345 template<typename T>
346 void swap(ArrayRef<T>& a, ArrayRef<T>& b)
347 {
348     a.swap(b);
349 }
350
351 /*! \brief Return a vector that is a copy of an ArrayRef.
352  *
353  * This makes it convenient, clear, and performant (the compiler will
354  * either do RVO to elide the temporary, or invoke the move constructor
355  * taking the unnamed temporary) to write a declaration like
356  *
357  *   auto v = copyOf(arrayRef);
358  *
359  * \ingroup module_utility
360  */
361 template<typename T>
362 std::vector<T> copyOf(const ArrayRef<const T>& arrayRef)
363 {
364     return std::vector<T>(arrayRef.begin(), arrayRef.end());
365 }
366
367 } // namespace gmx
368
369 #endif