Skip to content

Commit 24cc295

Browse files
authored
Merge pull request #1432 from anforowicz/slice-contiguous-range
Tweak `rust::Slice` to become a C++20 `contiguous_range`.
2 parents 58f7176 + 8b42fb9 commit 24cc295

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

book/src/binding/slice.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,11 @@ public:
5050
...template <typename T>
5151
...class Slice<T>::iterator final {
5252
...public:
53+
...#if __cplusplus >= 202002L
54+
... using iterator_category = std::contiguous_iterator_tag;
55+
...#else
5356
... using iterator_category = std::random_access_iterator_tag;
57+
...#endif
5458
... using value_type = T;
5559
... using pointer = T *;
5660
... using reference = T &;

include/cxx.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,11 @@ class Slice final
216216
template <typename T>
217217
class Slice<T>::iterator final {
218218
public:
219+
#if __cplusplus >= 202002L
220+
using iterator_category = std::contiguous_iterator_tag;
221+
#else
219222
using iterator_category = std::random_access_iterator_tag;
223+
#endif
220224
using value_type = T;
221225
using difference_type = std::ptrdiff_t;
222226
using pointer = typename std::add_pointer<T>::type;
@@ -234,6 +238,9 @@ class Slice<T>::iterator final {
234238
iterator &operator+=(difference_type) noexcept;
235239
iterator &operator-=(difference_type) noexcept;
236240
iterator operator+(difference_type) const noexcept;
241+
friend inline iterator operator+(difference_type lhs, iterator rhs) {
242+
return rhs + lhs;
243+
}
237244
iterator operator-(difference_type) const noexcept;
238245
difference_type operator-(const iterator &) const noexcept;
239246

@@ -249,6 +256,12 @@ class Slice<T>::iterator final {
249256
void *pos;
250257
std::size_t stride;
251258
};
259+
260+
#if __cplusplus >= 202002L
261+
static_assert(std::ranges::contiguous_range<rust::Slice<const uint8_t>>);
262+
static_assert(std::contiguous_iterator<rust::Slice<const uint8_t>::iterator>);
263+
#endif
264+
252265
#endif // CXXBRIDGE1_RUST_SLICE
253266

254267
#ifndef CXXBRIDGE1_RUST_BOX

0 commit comments

Comments
 (0)