Skip to content

[reland][libc] Add reverse_iterator comparisons #86188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions libc/src/__support/CPP/iterator.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ namespace cpp {
template <typename T> struct iterator_traits;
template <typename T> struct iterator_traits<T *> {
using reference = T &;
using value_type = T;
};

template <typename Iter> class reverse_iterator {
Iter current;

public:
using reference = typename iterator_traits<Iter>::reference;
using value_type = typename iterator_traits<Iter>::value_type;
using iterator_type = Iter;

LIBC_INLINE reverse_iterator() : current() {}
LIBC_INLINE constexpr explicit reverse_iterator(Iter it) : current(it) {}
Expand All @@ -38,6 +41,38 @@ template <typename Iter> class reverse_iterator {
LIBC_INLINE constexpr explicit reverse_iterator(const Other &it)
: current(it) {}

LIBC_INLINE friend constexpr bool operator==(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() == rhs.base();
}

LIBC_INLINE friend constexpr bool operator!=(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() != rhs.base();
}

LIBC_INLINE friend constexpr bool operator<(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() > rhs.base();
}

LIBC_INLINE friend constexpr bool operator<=(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() >= rhs.base();
}

LIBC_INLINE friend constexpr bool operator>(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() < rhs.base();
}

LIBC_INLINE friend constexpr bool operator>=(const reverse_iterator &lhs,
const reverse_iterator &rhs) {
return lhs.base() <= rhs.base();
}

LIBC_INLINE constexpr iterator_type base() const { return current; }

LIBC_INLINE constexpr reference operator*() const {
Iter tmp = current;
return *--tmp;
Expand Down