Remove some checks of .empty()
[external/binutils.git] / gdb / gdbsupport / next-iterator.h
1 /* A "next" iterator for GDB, the GNU debugger.
2    Copyright (C) 2019 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #ifndef COMMON_NEXT_ITERATOR_H
20 #define COMMON_NEXT_ITERATOR_H
21
22 /* An iterator that uses the 'next' field of a type to iterate.  This
23    can be used with various GDB types that are stored as linked
24    lists.  */
25
26 template<typename T>
27 struct next_iterator
28 {
29   typedef next_iterator self_type;
30   typedef T *value_type;
31   typedef T *&reference;
32   typedef T **pointer;
33   typedef std::forward_iterator_tag iterator_category;
34   typedef int difference_type;
35
36   explicit next_iterator (T *item)
37     : m_item (item)
38   {
39   }
40
41   /* Create a one-past-the-end iterator.  */
42   next_iterator ()
43     : m_item (nullptr)
44   {
45   }
46
47   value_type operator* () const
48   {
49     return m_item;
50   }
51
52   bool operator== (const self_type &other) const
53   {
54     return m_item == other.m_item;
55   }
56
57   bool operator!= (const self_type &other) const
58   {
59     return m_item != other.m_item;
60   }
61
62   self_type &operator++ ()
63   {
64     m_item = m_item->next;
65     return *this;
66   }
67
68 private:
69
70   T *m_item;
71 };
72
73 /* A range adapter that allows iterating over a linked list.  */
74
75 template<typename T, typename Iterator = next_iterator<T>>
76 class next_adapter
77 {
78 public:
79
80   explicit next_adapter (T *item)
81     : m_item (item)
82   {
83   }
84
85   using iterator = Iterator;
86
87   iterator begin () const
88   {
89     return iterator (m_item);
90   }
91
92   iterator end () const
93   {
94     return iterator ();
95   }
96
97 private:
98
99   T *m_item;
100 };
101
102 #endif /* COMMON_NEXT_ITERATOR_H */