MCPcopy Create free account
hub / github.com/astercloud/aster / Take

Function Take

pkg/stream/stream.go:623–646  ·  view source on GitHub ↗

Take 返回只产出前 n 个值的读取器

(r *Reader[T], n int)

Source from the content-addressed store, hash-verified

621
622// Take 返回只产出前 n 个值的读取器
623func Take[T any](r *Reader[T], n int) *Reader[T] {
624 out, writer := Pipe[T](n)
625 count := 0
626
627 go func() {
628 defer writer.Close()
629 for count < n {
630 v, err := r.Recv()
631 if errors.Is(err, io.EOF) {
632 return
633 }
634 if err != nil {
635 writer.Send(*new(T), err)
636 return
637 }
638 if writer.Send(v, nil) {
639 return
640 }
641 count++
642 }
643 }()
644
645 return out
646}
647
648// ForEach 消费读取器中的所有值,对每个值调用 fn
649func ForEach[T any](r *Reader[T], fn func(T) error) error {

Callers 1

TestTakeFunction · 0.85

Calls 3

RecvMethod · 0.80
CloseMethod · 0.65
SendMethod · 0.45

Tested by 1

TestTakeFunction · 0.68