sing-box/experimental/libbox/iterator.go

57 lines
1.0 KiB
Go
Raw Normal View History

2022-10-25 12:55:00 +08:00
package libbox
import "github.com/sagernet/sing/common"
type StringIterator interface {
2024-06-18 17:49:06 +08:00
Len() int32
2022-10-25 12:55:00 +08:00
HasNext() bool
2024-06-18 17:49:06 +08:00
Next() string
2022-10-25 12:55:00 +08:00
}
var _ StringIterator = (*iterator[string])(nil)
type iterator[T any] struct {
values []T
}
func newIterator[T any](values []T) *iterator[T] {
return &iterator[T]{values}
}
2024-06-11 21:16:33 +08:00
func newPtrIterator[T any](values []T) *iterator[*T] {
return &iterator[*T]{common.Map(values, func(value T) *T { return &value })}
}
2024-06-18 17:49:06 +08:00
func (i *iterator[T]) Len() int32 {
return int32(len(i.values))
}
func (i *iterator[T]) HasNext() bool {
return len(i.values) > 0
}
2022-10-25 12:55:00 +08:00
func (i *iterator[T]) Next() T {
if len(i.values) == 0 {
return common.DefaultValue[T]()
}
nextValue := i.values[0]
i.values = i.values[1:]
return nextValue
}
2023-04-18 14:04:09 +08:00
type abstractIterator[T any] interface {
Next() T
HasNext() bool
}
func iteratorToArray[T any](iterator abstractIterator[T]) []T {
if iterator == nil {
return nil
}
var values []T
for iterator.HasNext() {
values = append(values, iterator.Next())
}
return values
}