File: span.hh

package info (click to toggle)
dune-common 2.10.0-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,824 kB
  • sloc: cpp: 52,256; python: 3,979; sh: 1,658; makefile: 17
file content (453 lines) | stat: -rw-r--r-- 14,772 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
// SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
#ifndef DUNE_COMMON_STD_SPAN_HH
#define DUNE_COMMON_STD_SPAN_HH

#include <cassert>
#include <cstddef>
#include <exception>
#include <iterator>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>
#if __has_include(<version>)
  #include <version>
#endif

#include <dune/common/exceptions.hh>
#include <dune/common/std/memory.hh>

namespace Dune::Std {

/// \brief A constant of type std::size_t that is used to differentiate std::span of static and dynamic extent.
inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max();

namespace Impl {

template <std::size_t Extent>
class SpanSize
{
public:
  using size_type = std::size_t;

public:
  constexpr SpanSize () = default;

  constexpr SpanSize ([[maybe_unused]] size_type size) noexcept
  {
    assert(Extent == Std::dynamic_extent || Extent == size);
  }

  template <class Iter>
  constexpr SpanSize ([[maybe_unused]] Iter first, [[maybe_unused]] Iter last) noexcept
  {
    assert((std::distance(first,last) == Extent));
  }

  constexpr size_type size () const noexcept { return Extent; }
};

template <>
class SpanSize<Std::dynamic_extent>
{
public:
  using size_type = std::size_t;

public:
  constexpr SpanSize (size_type size = 0) noexcept
    : size_(size)
  {}

  template <class Iter>
  constexpr SpanSize (Iter first, Iter last) noexcept
    : size_(std::distance(first,last))
  {}

  constexpr size_type size () const noexcept { return size_; }

private:
  size_type size_;
};

template <class T>
struct TypeIdentity { using type = T; };

template <class T>
using TypeIdentity_t = typename TypeIdentity<T>::type;

} // end namespace Impl


/**
 * \brief A contiguous sequence of elements with static or dynamic extent.
 * \ingroup CxxUtilities
 * \nosubgrouping
 *
 * The class template span describes an object that can refer to a contiguous sequence
 * of objects with the first element of the sequence at position zero. A span can either
 * have a static extent, in which case the number of elements in the sequence is known
 * at compile-time and encoded in the type, or a dynamic extent.
 *
 * If a span has dynamic extent, a typical implementation holds two members: a pointer
 * to `Element` and a size. A span with static extent may have only one member: a pointer
 * to `Element`.
 *
 * The implementation is based on the C++ standard working draft
 * <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4971.pdf">N4971</a> and
 * the documentation provided in
 * <a href="https://en.cppreference.com/w/cpp/container/span">cppreference</a>.
 *
 * \b Example:
 * \code{.cpp}
    std::vector v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // view data as contiguous memory representing 10 elements
    auto s1 = Dune::Std::span(v.data(), 10);

    // view data as contiguous memory with static size
    auto s2 = Dune::Std::span<int,10>(v.data());

    // write data using 2D view
    for (std::size_t i = 0; i != s1.size(); i++)
      s1[i] = 2*i;
 * \endcode
 *
 * \tparam Element  The element type; a complete object type that is not an abstract class type.
 * \tparam Extent   Specifies number of elements in the sequence, or `Std::dynamic_extent` if dynamic.
 *
 * \related Std::dynamic_extent
 **/
template <class Element, std::size_t Extent = Std::dynamic_extent>
class span
    : public Impl::SpanSize<Extent>
{
  using base_type = Impl::SpanSize<Extent>; // base_type implements the member variable size()

  static_assert(std::is_object_v<Element> && !std::is_abstract_v<Element>);

public:
  using element_type = Element;
  using value_type = std::remove_cv_t<element_type>;
  using size_type = std::size_t;
  using difference_type = std::ptrdiff_t;
  using pointer = element_type*;
  using reference = element_type&;
  using const_reference  = const element_type&;
  using iterator = pointer;
  using reverse_iterator = std::reverse_iterator<iterator>;
#if __cpp_lib_ranges_as_const >202311L
  using const_iterator = std::const_iterator<iterator>;
  using const_reverse_iterator = std::const_iterator<reverse_iterator>;
#else
  using const_iterator = const iterator;
  using const_reverse_iterator = std::reverse_iterator<const_iterator>;
#endif


  static constexpr size_type extent = Extent;

public:
  /// \name Span constructors
  /// @{

  /// \brief Default construct an empty span
  template <std::size_t e = extent,
    std::enable_if_t<(e == dynamic_extent || e == 0), int> = 0>
  constexpr span () noexcept
    : base_type{}
    , data_{}
  {}

  /// \brief Constructs a span that is a view over the range `[first, first+size)`
  template <class Iter,
    class U = std::remove_reference_t<decltype(*std::declval<Iter>())>,
    std::enable_if_t<std::is_convertible_v<U(*)[], element_type(*)[]>, int> = 0>
  #if __cpp_conditional_explicit >= 201806L
  explicit(extent != Std::dynamic_extent)
  #endif
  constexpr span (Iter first, size_type size)
    : base_type(size)
    , data_(Std::to_address(first))
  {}

  /// \brief Constructs a span that is a view over the range `[first, last)`
  template <class Iter,
    class U = std::remove_reference_t<decltype(*std::declval<Iter>())>,
    std::enable_if_t<std::is_convertible_v<U(*)[], element_type(*)[]>, int> = 0>
  #if __cpp_conditional_explicit >= 201806L
  explicit(extent != Std::dynamic_extent)
  #endif
  constexpr span (Iter first, Iter last)
    : base_type(first,last)
    , data_(Std::to_address(first))
  {}

  /// \brief Constructs a span that is a view over the range `[range.begin(), range.end())`
  template <class Range,
    decltype(std::begin(std::declval<Range>()), std::end(std::declval<Range>()), bool{}) = true,
    std::enable_if_t<not std::is_array_v<Range>, int> = 0>
  #if __cpp_conditional_explicit >= 201806L
  explicit(extent != Std::dynamic_extent)
  #endif
  constexpr span (Range& range)
    : span(std::begin(range), std::end(range))
  {}

  /// \brief Constructs a span that is a view over the C-array
  template <std::size_t N, std::size_t e = extent,
    std::enable_if_t<(e == Std::dynamic_extent || e == N), int> = 0>
  constexpr span (Impl::TypeIdentity_t<element_type> (&data)[N]) noexcept
    : base_type(N)
    , data_(data)
  {}

  /// \brief Constructs a span that is a view over the array
  template <class T, size_t N, std::size_t e = extent,
    std::enable_if_t<(e == Std::dynamic_extent || e == N), int> = 0,
    std::enable_if_t<std::is_convertible_v<T(*)[], element_type(*)[]>, int> = 0>
  constexpr span (std::array<T, N>& arr) noexcept
    : base_type(N)
    , data_(arr.data())
  {}

  /// \brief Constructs a span that is a view over the const array
  template <class T, size_t N, std::size_t e = extent,
    std::enable_if_t<(e == Std::dynamic_extent || e == N), int> = 0,
    std::enable_if_t<std::is_convertible_v<const T(*)[], element_type(*)[]>, int> = 0>
  constexpr span (const std::array<T, N>& arr) noexcept
    : base_type(N)
    , data_(arr.data())
  {}

  /// \brief Constructs a span that is a view over the initializer-list
  template <class E = element_type,
    std::enable_if_t<std::is_const_v<E>, int> = 0>
  #if __cpp_conditional_explicit >= 201806L
  explicit(extent != Std::dynamic_extent)
  #endif
  constexpr span (std::initializer_list<value_type> il)
    : base_type(il.size())
    , data_(il.begin())
  {}

  /// \brief Copy constructor
  constexpr span (const span& other) noexcept = default;

  /// \brief Converting copy constructor
  template <class OtherElementType, std::size_t OtherExtent,
    std::enable_if_t<(extent == Std::dynamic_extent || OtherExtent == Std::dynamic_extent || extent == OtherExtent), int> = 0,
    std::enable_if_t<std::is_convertible_v<OtherElementType(*)[], element_type(*)[]>, int> = 0>
  #if __cpp_conditional_explicit >= 201806L
  explicit(extent != Std::dynamic_extent && OtherExtent == Std::dynamic_extent)
  #endif
  constexpr span (const span<OtherElementType, OtherExtent>& s) noexcept
    : base_type(s.size())
    , data_(s.data())
  {}

  /// \brief Copy assignment operator
  constexpr span& operator= (const span& other) noexcept = default;

  /// @}


  /// \name Iterators
  /// @{

  /// \brief Returns an iterator to the beginning.
  constexpr iterator begin () const noexcept { return data_; }

  /// \brief Returns an iterator to the end.
  constexpr iterator end () const noexcept { return data_ + size(); }

  /// \brief Returns an iterator to the beginning.
  constexpr const_iterator cbegin () const noexcept { return data_; }

  /// \brief Returns an iterator to the end.
  constexpr const_iterator cend () const noexcept { return data_ + size(); }

  /// \brief Returns a reverse iterator starting at the end.
  constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; }

  /// \brief Returns a reverse iterator ending at the beginning.
  constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; }

  /// \brief Returns a reverse iterator starting at the end.
  constexpr const_reverse_iterator  crbegin() const noexcept { return reverse_iterator{end()}; }

  /// \brief Returns a reverse iterator ending at the beginning.
  constexpr const_reverse_iterator  crend() const noexcept { return reverse_iterator{begin()}; }

  /// @}


  /// \name Element and data access
  /// @{

  /// \brief Access the first element.
  constexpr reference front () const
  {
    assert(not empty() && "front of empty span does not exist");
    return data_[0];
  }

  /// \brief Access the last element.
  constexpr reference back () const
  {
    assert(not empty() && "front of empty span does not exist");
    return data_[size()-1];
  }

  /// \brief Access specified element with bounds checking.
  constexpr reference at (size_type i) const
  {
    if (i >= size())
      throw std::out_of_range("Index " + std::to_string(i) + " out of range.");
    return data_[i];
  }

  /// \brief Access specified element.
  constexpr reference operator[] (size_type i) const { return data_[i]; }

  /// \brief Direct access to the underlying contiguous storage
  constexpr pointer data () const noexcept { return data_; }

  /// @}


  /// \name Subspans
  /// @{

  /// \brief Obtains a subspan consisting of the first `Count` elements of the sequence
  template <std::size_t Count>
  constexpr span<element_type, Count> first () const
  {
    static_assert(Count <= Extent);
    assert(Count <= size());
    return span<element_type, Count>{data(), Count};
  }

  /// \brief Obtains a subspan consisting of the last `Count` elements of the sequence
  template <std::size_t Count>
  constexpr span<element_type, Count> last () const
  {
    static_assert(Count <= Extent);
    assert(Count <= size());
    return span<element_type, Count>{data()+ (size() - Count), Count};
  }

private:

  static constexpr std::size_t subspan_extent (std::size_t O, std::size_t C) noexcept
  {
    return (C != Std::dynamic_extent) ? C :
      (Extent != Std::dynamic_extent) ? Extent - O : Std::dynamic_extent;
  }

public:

  /// \brief Obtains a subspan consisting of `Count` elements of the sequence starting at `Offset`.
  /**
   * \note If `Count == Std::dynamic_extent`, the subspan starting at `Offset` goes
   * until the end of the current span.
   */
  template <std::size_t Offset, std::size_t Count = Std::dynamic_extent>
  constexpr span<element_type, subspan_extent(Offset,Count)> subspan () const
  {
    static_assert(Offset <= Extent && (Count == Std::dynamic_extent || Count <= Extent - Offset));
    assert(Offset <= size() && (Count == Std::dynamic_extent || Count <= size() - Offset));
    return span<element_type, subspan_extent(Offset,Count)>{
      data() + Offset, Count != Std::dynamic_extent ? Count : size() - Offset};
  }

  /// \brief Obtains a subspan consisting of the first `count` elements of the sequence
  constexpr span<element_type, Std::dynamic_extent> first (size_type count) const
  {
    assert(count <= size());
    return span<element_type, Std::dynamic_extent>{data(), count};
  }

  /// \brief Obtains a subspan consisting of the last `count` elements of the sequence
  constexpr span<element_type, Std::dynamic_extent> last (size_type count) const
  {
    assert(count <= size());
    return span<element_type, Std::dynamic_extent>{data()+ (size() - count), count};
  }

  /// \brief Obtains a subspan consisting of `count` elements of the sequence starting at `offset`.
  /**
   * \note If `count == Std::dynamic_extent`, the subspan starting at `offset` goes
   * until the end of the current span.
   */
  constexpr span<element_type, Std::dynamic_extent> subspan (size_type offset, size_type count = Std::dynamic_extent) const
  {
    assert(offset <= size() && (count == Std::dynamic_extent || count <= size() - offset));
    return span<element_type, Std::dynamic_extent>{
      data() + offset, count == Std::dynamic_extent ? size() - offset : count};
  }

  /// @}


  /// \name Size information
  /// @{

  /// \brief Returns the number of elements.
  using base_type::size;

  /// \brief Returns the size of the sequence in bytes.
  constexpr size_type size_bytes () const noexcept { return size() * sizeof(element_type); }

  /// \brief Checks if the sequence is empty.
  [[nodiscard]] constexpr bool empty () const noexcept { return size() == 0; }

  /// @}

private:
  pointer data_;
};

// deduction guide
// @{

template <class T, std::size_t N>
span (T (&)[N])
  -> span<T, N>;

template <class ElementType, class I, std::size_t Extent,
  std::enable_if_t<std::is_convertible_v<I,std::size_t>, int> = 0>
span (ElementType*, std::integral_constant<I,Extent>)
  -> span<ElementType, Extent>;

template <class ElementType, class I,
  std::enable_if_t<std::is_integral_v<I>, int> = 0,
  std::enable_if_t<std::is_convertible_v<I,std::size_t>, int> = 0>
span (ElementType*, I)
  -> span<ElementType, Std::dynamic_extent>;

template <class Iter,
  class Element = std::remove_reference_t<decltype(*std::declval<Iter>())>>
span (Iter,Iter)
  -> span<Element, Std::dynamic_extent>;

template <class Range,
  class First = decltype(std::begin(std::declval<Range>())),
  class Last = decltype(std::end(std::declval<Range>())),
  class Element = std::remove_reference_t<decltype(*std::declval<First>())>>
span (Range&)
  -> span<Element, Std::dynamic_extent>;

template <class T, size_t N>
span (std::array<T, N>&) -> span<T, N>;

template <class T, size_t N>
span (const std::array<T, N>&) -> span<const T, N>;

// @}

} // end namespace Dune::Std

#endif // DUNE_COMMON_STD_SPAN_HH