github.com/haraldrudell/parl@v0.4.176/pio/context-reader-x.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pio
     7  
     8  import (
     9  	"context"
    10  	"io"
    11  )
    12  
    13  // ContextReader reader terminated by context
    14  type ContextReaderX struct {
    15  	ctx context.Context
    16  	io.Reader
    17  }
    18  
    19  // NewContextReader instantiates ContextReader
    20  func NewContextReaderX(ctx context.Context, reader io.Reader) io.Reader {
    21  	return &ContextReaderX{ctx: ctx, Reader: reader}
    22  }
    23  
    24  func (cr *ContextReaderX) Read(p []byte) (n int, err error) {
    25  	if err := cr.ctx.Err(); err != nil {
    26  		return 0, err
    27  	}
    28  	return cr.Reader.Read(p)
    29  }