/* An iterator class that iterates on integer arrays. Copyright (C) 2019-2026 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef GDB_UNITTESTS_INT_ARRAY_ITERATOR_H #define GDB_UNITTESTS_INT_ARRAY_ITERATOR_H #include "gdbsupport/selftest.h" #include namespace selftests { struct int_array_iterator { using value_type = int; using reference = int &; using pointer = int *; using iterator_category = std::forward_iterator_tag; using difference_type = int; /* Create an iterator that points at the first element of an integer array at ARRAY of size SIZE. */ int_array_iterator (int *array, size_t size) : m_array (array), m_size (size) {} /* Create a past-the-end iterator. */ int_array_iterator () : m_array (nullptr), m_size (0) {} bool operator== (const int_array_iterator &other) const { /* If both are past-the-end, they are equal. */ if (m_array == nullptr && other.m_array == nullptr) return true; /* If just one of them is past-the-end, they are not equal. */ if (m_array == nullptr || other.m_array == nullptr) return false; /* If they are both not past-the-end, make sure they iterate on the same array (we shouldn't compare iterators that iterate on different things). */ SELF_CHECK (m_array == other.m_array); /* They are equal if they have the same current index. */ return m_cur_idx == other.m_cur_idx; } bool operator!= (const int_array_iterator &other) const { return !(*this == other); } void operator++ () { /* Make sure nothing tries to increment a past the end iterator. */ SELF_CHECK (m_cur_idx < m_size); m_cur_idx++; /* Mark the iterator as "past-the-end" if we have reached the end. */ if (m_cur_idx == m_size) m_array = nullptr; } int operator* () const { /* Make sure nothing tries to dereference a past the end iterator. */ SELF_CHECK (m_cur_idx < m_size); return m_array[m_cur_idx]; } private: /* A nullptr value in M_ARRAY indicates a past-the-end iterator. */ int *m_array; size_t m_size; size_t m_cur_idx = 0; }; } /* namespace selftests */ #endif /* GDB_UNITTESTS_INT_ARRAY_ITERATOR_H */