Source file src/iter/iter.go
1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 /* 6 Package iter provides basic definitions and operations related to 7 iterators over sequences. 8 9 # Iterators 10 11 An iterator is a function that passes successive elements of a 12 sequence to a callback function, conventionally named yield. 13 The function stops either when the sequence is finished or 14 when yield returns false, indicating to stop the iteration early. 15 This package defines [Seq] and [Seq2] 16 (pronounced like seek—the first syllable of sequence) 17 as shorthands for iterators that pass 1 or 2 values per sequence element 18 to yield: 19 20 type ( 21 Seq[V any] func(yield func(V) bool) 22 Seq2[K, V any] func(yield func(K, V) bool) 23 ) 24 25 Seq2 represents a sequence of paired values, conventionally key-value 26 or index-value pairs. 27 28 Yield returns true if the iterator should continue with the next 29 element in the sequence, false if it should stop. 30 31 Yield panics if called after it returns false. 32 33 For instance, [maps.Keys] returns an iterator that produces the sequence 34 of keys of the map m, implemented as follows: 35 36 func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] { 37 return func(yield func(K) bool) { 38 for k := range m { 39 if !yield(k) { 40 return 41 } 42 } 43 } 44 } 45 46 Further examples can be found in [The Go Blog: Range Over Function Types]. 47 48 Iterator functions are most often called by a [range loop], as in: 49 50 func PrintAll[V any](seq iter.Seq[V]) { 51 for v := range seq { 52 fmt.Println(v) 53 } 54 } 55 56 # Naming Conventions 57 58 Iterator functions and methods are named for the sequence being walked: 59 60 // All returns an iterator over all elements in s. 61 func (s *Set[V]) All() iter.Seq[V] 62 63 The iterator method on a collection type is conventionally named All, 64 because it iterates a sequence of all the values in the collection. 65 66 For a type containing multiple possible sequences, the iterator's name 67 can indicate which sequence is being provided: 68 69 // Cities returns an iterator over the major cities in the country. 70 func (c *Country) Cities() iter.Seq[*City] 71 72 // Languages returns an iterator over the official spoken languages of the country. 73 func (c *Country) Languages() iter.Seq[string] 74 75 If an iterator requires additional configuration, the constructor function 76 can take additional configuration arguments: 77 78 // Scan returns an iterator over key-value pairs with min ≤ key ≤ max. 79 func (m *Map[K, V]) Scan(min, max K) iter.Seq2[K, V] 80 81 // Split returns an iterator over the (possibly-empty) substrings of s 82 // separated by sep. 83 func Split(s, sep string) iter.Seq[string] 84 85 When there are multiple possible iteration orders, the method name may 86 indicate that order: 87 88 // All returns an iterator over the list from head to tail. 89 func (l *List[V]) All() iter.Seq[V] 90 91 // Backward returns an iterator over the list from tail to head. 92 func (l *List[V]) Backward() iter.Seq[V] 93 94 // Preorder returns an iterator over all nodes of the syntax tree 95 // beneath (and including) the specified root, in depth-first preorder, 96 // visiting a parent node before its children. 97 func Preorder(root Node) iter.Seq[Node] 98 99 # Single-Use Iterators 100 101 Most iterators provide the ability to walk an entire sequence: 102 when called, the iterator does any setup necessary to start the 103 sequence, then calls yield on successive elements of the sequence, 104 and then cleans up before returning. Calling the iterator again 105 walks the sequence again. 106 107 Some iterators break that convention, providing the ability to walk a 108 sequence only once. These “single-use iterators” typically report values 109 from a data stream that cannot be rewound to start over. 110 Calling the iterator again after stopping early may continue the 111 stream, but calling it again after the sequence is finished will yield 112 no values at all. Doc comments for functions or methods that return 113 single-use iterators should document this fact: 114 115 // Lines returns an iterator over lines read from r. 116 // It returns a single-use iterator. 117 func (r *Reader) Lines() iter.Seq[string] 118 119 # Pulling Values 120 121 Functions and methods that accept or return iterators 122 should use the standard [Seq] or [Seq2] types, to ensure 123 compatibility with range loops and other iterator adapters. 124 The standard iterators can be thought of as “push iterators”, which 125 push values to the yield function. 126 127 Sometimes a range loop is not the most natural way to consume values 128 of the sequence. In this case, [Pull] converts a standard push iterator 129 to a “pull iterator”, which can be called to pull one value at a time 130 from the sequence. [Pull] starts an iterator and returns a pair 131 of functions—next and stop—which return the next value from the iterator 132 and stop it, respectively. 133 134 For example: 135 136 // Pairs returns an iterator over successive pairs of values from seq. 137 func Pairs[V any](seq iter.Seq[V]) iter.Seq2[V, V] { 138 return func(yield func(V, V) bool) { 139 next, stop := iter.Pull(seq) 140 defer stop() 141 for { 142 v1, ok1 := next() 143 if !ok1 { 144 return 145 } 146 v2, ok2 := next() 147 // If ok2 is false, v2 should be the 148 // zero value; yield one last pair. 149 if !yield(v1, v2) { 150 return 151 } 152 if !ok2 { 153 return 154 } 155 } 156 } 157 } 158 159 If clients do not consume the sequence to completion, they must call stop, 160 which allows the iterator function to finish and return. As shown in 161 the example, the conventional way to ensure this is to use defer. 162 163 # Standard Library Usage 164 165 A few packages in the standard library provide iterator-based APIs, 166 most notably the [maps] and [slices] packages. 167 For example, [maps.Keys] returns an iterator over the keys of a map, 168 while [slices.Sorted] collects the values of an iterator into a slice, 169 sorts them, and returns the slice, so to iterate over the sorted keys of a map: 170 171 for _, key := range slices.Sorted(maps.Keys(m)) { 172 ... 173 } 174 175 # Mutation 176 177 Iterators provide only the values of the sequence, not any direct way 178 to modify it. If an iterator wishes to provide a mechanism for modifying 179 a sequence during iteration, the usual approach is to define a position type 180 with the extra operations and then provide an iterator over positions. 181 182 For example, a tree implementation might provide: 183 184 // Positions returns an iterator over positions in the sequence. 185 func (t *Tree[V]) Positions() iter.Seq[*Pos[V]] 186 187 // A Pos represents a position in the sequence. 188 // It is only valid during the yield call it is passed to. 189 type Pos[V any] struct { ... } 190 191 // Pos returns the value at the cursor. 192 func (p *Pos[V]) Value() V 193 194 // Delete deletes the value at this point in the iteration. 195 func (p *Pos[V]) Delete() 196 197 // Set changes the value v at the cursor. 198 func (p *Pos[V]) Set(v V) 199 200 And then a client could delete boring values from the tree using: 201 202 for p := range t.Positions() { 203 if boring(p.Value()) { 204 p.Delete() 205 } 206 } 207 208 [The Go Blog: Range Over Function Types]: https://go.dev/blog/range-functions 209 [range loop]: https://go.dev/ref/spec#For_range 210 */ 211 package iter 212 213 import ( 214 "internal/race" 215 "runtime" 216 "unsafe" 217 ) 218 219 // Seq is an iterator over sequences of individual values. 220 // When called as seq(yield), seq calls yield(v) for each value v in the sequence, 221 // stopping early if yield returns false. 222 // See the [iter] package documentation for more details. 223 type Seq[V any] func(yield func(V) bool) 224 225 // Seq2 is an iterator over sequences of pairs of values, most commonly key-value pairs. 226 // When called as seq(yield), seq calls yield(k, v) for each pair (k, v) in the sequence, 227 // stopping early if yield returns false. 228 // See the [iter] package documentation for more details. 229 type Seq2[K, V any] func(yield func(K, V) bool) 230 231 type coro struct{} 232 233 //go:linkname newcoro runtime.newcoro 234 func newcoro(func(*coro)) *coro 235 236 //go:linkname coroswitch runtime.coroswitch 237 func coroswitch(*coro) 238 239 // Pull converts the “push-style” iterator sequence seq 240 // into a “pull-style” iterator accessed by the two functions 241 // next and stop. 242 // 243 // Next returns the next value in the sequence 244 // and a boolean indicating whether the value is valid. 245 // When the sequence is over, next returns the zero V and false. 246 // It is valid to call next after reaching the end of the sequence 247 // or after calling stop. These calls will continue 248 // to return the zero V and false. 249 // 250 // Stop ends the iteration. It must be called when the caller is 251 // no longer interested in next values and next has not yet 252 // signaled that the sequence is over (with a false boolean return). 253 // It is valid to call stop multiple times and when next has 254 // already returned false. Typically, callers should “defer stop()”. 255 // 256 // It is an error to call next or stop from multiple goroutines 257 // simultaneously. 258 // 259 // If the iterator panics during a call to next (or stop), 260 // then next (or stop) itself panics with the same value. 261 func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func()) { 262 var pull struct { 263 v V 264 ok bool 265 done bool 266 yieldNext bool 267 seqDone bool // to detect Goexit 268 racer int 269 panicValue any 270 } 271 c := newcoro(func(c *coro) { 272 race.Acquire(unsafe.Pointer(&pull.racer)) 273 if pull.done { 274 race.Release(unsafe.Pointer(&pull.racer)) 275 return 276 } 277 yield := func(v1 V) bool { 278 if pull.done { 279 return false 280 } 281 if !pull.yieldNext { 282 panic("iter.Pull: yield called again before next") 283 } 284 pull.yieldNext = false 285 pull.v, pull.ok = v1, true 286 race.Release(unsafe.Pointer(&pull.racer)) 287 coroswitch(c) 288 race.Acquire(unsafe.Pointer(&pull.racer)) 289 return !pull.done 290 } 291 // Recover and propagate panics from seq. 292 defer func() { 293 if p := recover(); p != nil { 294 pull.panicValue = p 295 } else if !pull.seqDone { 296 pull.panicValue = goexitPanicValue 297 } 298 pull.done = true // Invalidate iterator 299 race.Release(unsafe.Pointer(&pull.racer)) 300 }() 301 seq(yield) 302 var v0 V 303 pull.v, pull.ok = v0, false 304 pull.seqDone = true 305 }) 306 next = func() (v1 V, ok1 bool) { 307 race.Write(unsafe.Pointer(&pull.racer)) // detect races 308 309 if pull.done { 310 return 311 } 312 if pull.yieldNext { 313 panic("iter.Pull: next called again before yield") 314 } 315 pull.yieldNext = true 316 race.Release(unsafe.Pointer(&pull.racer)) 317 coroswitch(c) 318 race.Acquire(unsafe.Pointer(&pull.racer)) 319 320 // Propagate panics and goexits from seq. 321 if pull.panicValue != nil { 322 if pull.panicValue == goexitPanicValue { 323 // Propagate runtime.Goexit from seq. 324 runtime.Goexit() 325 } else { 326 panic(pull.panicValue) 327 } 328 } 329 return pull.v, pull.ok 330 } 331 stop = func() { 332 race.Write(unsafe.Pointer(&pull.racer)) // detect races 333 334 if !pull.done { 335 pull.done = true 336 race.Release(unsafe.Pointer(&pull.racer)) 337 coroswitch(c) 338 race.Acquire(unsafe.Pointer(&pull.racer)) 339 340 // Propagate panics and goexits from seq. 341 if pull.panicValue != nil { 342 if pull.panicValue == goexitPanicValue { 343 // Propagate runtime.Goexit from seq. 344 runtime.Goexit() 345 } else { 346 panic(pull.panicValue) 347 } 348 } 349 } 350 } 351 return next, stop 352 } 353 354 // Pull2 converts the “push-style” iterator sequence seq 355 // into a “pull-style” iterator accessed by the two functions 356 // next and stop. 357 // 358 // Next returns the next pair in the sequence 359 // and a boolean indicating whether the pair is valid. 360 // When the sequence is over, next returns a pair of zero values and false. 361 // It is valid to call next after reaching the end of the sequence 362 // or after calling stop. These calls will continue 363 // to return a pair of zero values and false. 364 // 365 // Stop ends the iteration. It must be called when the caller is 366 // no longer interested in next values and next has not yet 367 // signaled that the sequence is over (with a false boolean return). 368 // It is valid to call stop multiple times and when next has 369 // already returned false. Typically, callers should “defer stop()”. 370 // 371 // It is an error to call next or stop from multiple goroutines 372 // simultaneously. 373 // 374 // If the iterator panics during a call to next (or stop), 375 // then next (or stop) itself panics with the same value. 376 func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func()) { 377 var pull struct { 378 k K 379 v V 380 ok bool 381 done bool 382 yieldNext bool 383 seqDone bool 384 racer int 385 panicValue any 386 } 387 c := newcoro(func(c *coro) { 388 race.Acquire(unsafe.Pointer(&pull.racer)) 389 if pull.done { 390 race.Release(unsafe.Pointer(&pull.racer)) 391 return 392 } 393 yield := func(k1 K, v1 V) bool { 394 if pull.done { 395 return false 396 } 397 if !pull.yieldNext { 398 panic("iter.Pull2: yield called again before next") 399 } 400 pull.yieldNext = false 401 pull.k, pull.v, pull.ok = k1, v1, true 402 race.Release(unsafe.Pointer(&pull.racer)) 403 coroswitch(c) 404 race.Acquire(unsafe.Pointer(&pull.racer)) 405 return !pull.done 406 } 407 // Recover and propagate panics from seq. 408 defer func() { 409 if p := recover(); p != nil { 410 pull.panicValue = p 411 } else if !pull.seqDone { 412 pull.panicValue = goexitPanicValue 413 } 414 pull.done = true // Invalidate iterator. 415 race.Release(unsafe.Pointer(&pull.racer)) 416 }() 417 seq(yield) 418 var k0 K 419 var v0 V 420 pull.k, pull.v, pull.ok = k0, v0, false 421 pull.seqDone = true 422 }) 423 next = func() (k1 K, v1 V, ok1 bool) { 424 race.Write(unsafe.Pointer(&pull.racer)) // detect races 425 426 if pull.done { 427 return 428 } 429 if pull.yieldNext { 430 panic("iter.Pull2: next called again before yield") 431 } 432 pull.yieldNext = true 433 race.Release(unsafe.Pointer(&pull.racer)) 434 coroswitch(c) 435 race.Acquire(unsafe.Pointer(&pull.racer)) 436 437 // Propagate panics and goexits from seq. 438 if pull.panicValue != nil { 439 if pull.panicValue == goexitPanicValue { 440 // Propagate runtime.Goexit from seq. 441 runtime.Goexit() 442 } else { 443 panic(pull.panicValue) 444 } 445 } 446 return pull.k, pull.v, pull.ok 447 } 448 stop = func() { 449 race.Write(unsafe.Pointer(&pull.racer)) // detect races 450 451 if !pull.done { 452 pull.done = true 453 race.Release(unsafe.Pointer(&pull.racer)) 454 coroswitch(c) 455 race.Acquire(unsafe.Pointer(&pull.racer)) 456 457 // Propagate panics and goexits from seq. 458 if pull.panicValue != nil { 459 if pull.panicValue == goexitPanicValue { 460 // Propagate runtime.Goexit from seq. 461 runtime.Goexit() 462 } else { 463 panic(pull.panicValue) 464 } 465 } 466 } 467 } 468 return next, stop 469 } 470 471 // goexitPanicValue is a sentinel value indicating that an iterator 472 // exited via runtime.Goexit. 473 var goexitPanicValue any = new(int) 474