| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package iprange |
| 4 | |
| 5 | import ( |
| 6 | "iter" |
| 7 | "net/netip" |
| 8 | ) |
| 9 | |
| 10 | // iterate returns an iterator that yields each IP address in the range. |
| 11 | // It handles both IPv4 and IPv6 ranges efficiently. |
| 12 | func iterate(r Range) iter.Seq[netip.Addr] { |
| 13 | return func(yield func(netip.Addr) bool) { |
| 14 | current := r.Start() |
| 15 | end := r.End() |
| 16 | |
| 17 | // Handle empty or invalid range |
| 18 | if !current.IsValid() || !end.IsValid() { |
| 19 | return |
| 20 | } |
| 21 | |
| 22 | for { |
| 23 | // Yield current address |
| 24 | if !yield(current) { |
| 25 | return |
| 26 | } |
| 27 | |
| 28 | // Check if we've reached the end |
| 29 | if current == end { |
| 30 | return |
| 31 | } |
| 32 | |
| 33 | // Move to next address |
| 34 | next := current.Next() |
| 35 | |
| 36 | // Check for overflow or going past the end |
| 37 | if !next.IsValid() || next.Compare(end) > 0 { |
| 38 | return |
| 39 | } |
| 40 | |
| 41 | current = next |
| 42 | } |
| 43 | } |
| 44 | } |