File: iterator.go

package info (click to toggle)
golang-github-juju-collections 1.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie, trixie-proposed-updates
  • size: 176 kB
  • sloc: makefile: 18
file content (53 lines) | stat: -rw-r--r-- 1,277 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2018 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package deque

import (
	"container/list"
	"reflect"
)

// Iterator allows in order iteration of the deque elements.
// The iterator is valid as long as no elements are added or removed from the deque.
type Iterator struct {
	deque *Deque
	elem  *list.Element
	block blockT
	index int
	pos   int
}

// Iterator returns an `Iterator` for in order iteration of the elements.
func (d *Deque) Iterator() Iterator {
	front := d.blocks.Front()
	return Iterator{
		deque: d,
		elem:  front,
		block: front.Value.(blockT),
		pos:   d.frontIdx - 1,
	}
}

// Next returns true if there is a value, and the value is populated with the
// next element. Next returns false if it is at the end and the value is
// unchanged. The `value` must be a pointer to the type stored in the deque.
func (i *Iterator) Next(value interface{}) bool {
	if i.index >= i.deque.Len() {
		return false
	}
	i.index++
	i.pos++
	if i.pos == blockLen {
		i.pos = 0
		i.elem = i.elem.Next()
		i.block = i.elem.Value.(blockT)
	}
	v := reflect.ValueOf(value)
	if v.Kind() != reflect.Ptr {
		panic("value is not a pointer")
	}
	v = v.Elem() // dereference the pointer
	v.Set(reflect.ValueOf(i.block[i.pos]))
	return true
}