slice.go 708 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package reader
  2. import (
  3. "context"
  4. "io"
  5. )
  6. type SliceReader[T any] struct {
  7. items []T
  8. pos int
  9. }
  10. func NewSliceReader[T any](items []T) *SliceReader[T] {
  11. return &SliceReader[T]{
  12. items: items,
  13. pos: 0,
  14. }
  15. }
  16. func (r *SliceReader[T]) Read(ctx context.Context, dst []T) (int, error) {
  17. if err := ctx.Err(); err != nil {
  18. return 0, err
  19. }
  20. if r.pos >= len(r.items) {
  21. return 0, io.EOF
  22. }
  23. n := copy(dst, r.items[r.pos:])
  24. r.pos += n
  25. // Fold the terminal signal into the final data-bearing read rather than
  26. // requiring a separate trailing call that returns (0, io.EOF).
  27. if r.pos >= len(r.items) {
  28. return n, io.EOF
  29. }
  30. return n, nil
  31. }
  32. func (r *SliceReader[T]) Close() error {
  33. return nil
  34. }