cancelreader

package module
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2022 License: MIT Imports: 7 Imported by: 17

README

CancelReader

Latest Release Go Doc Software License Build Status Go ReportCard

A cancelable reader for Go

This package is based on the fantastic work of Erik Geiser in Charm's Bubble Tea framework.

Usage

NewReader returns a reader with a Cancel function. If the input reader is a File, the cancel function can be used to interrupt a blocking Read call. In this case, the cancel function returns true if the call was canceled successfully. If the input reader is not a File, the cancel function does nothing and always returns false.

r, err := cancelreader.NewReader(file)
if err != nil {
    // handle error
    ...
}

// cancel after five seconds
go func() {
    time.Sleep(5 * time.Second)
    r.Cancel()
}()

// keep reading
for {
    var buf [1024]byte
    _, err := r.Read(buf[:])

    if errors.Is(err, cancelreader.ErrCanceled) {
        fmt.Println("canceled!")
        break
    }
    if err != nil {
        // handle other errors
        ...
    }

    // handle data
    ...
}

Implementations

  • The Linux implementation is based on the epoll mechanism
  • The BSD and macOS implementation is based on the kqueue mechanism
  • The generic Unix implementation is based on the posix select syscall

Caution

The Windows implementation is based on WaitForMultipleObject with overlapping reads from CONIN$. At this point it only supports canceling reads from os.Stdin.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrCanceled = fmt.Errorf("read canceled")

ErrCanceled gets returned when trying to read from a canceled reader.

Functions

This section is empty.

Types

type CancelReader

type CancelReader interface {
	io.ReadCloser

	// Cancel cancels ongoing and future reads an returns true if it succeeded.
	Cancel() bool
}

CancelReader is a io.Reader whose Read() calls can be canceled without data being consumed. The cancelReader has to be closed.

func NewReader

func NewReader(reader io.Reader) (CancelReader, error)

NewReader returns a reader and a cancel function. If the input reader is a File, the cancel function can be used to interrupt a blocking read call. In this case, the cancel function returns true if the call was canceled successfully. If the input reader is not a File, the cancel function does nothing and always returns false. The Linux implementation is based on the epoll mechanism.

type File added in v0.2.0

type File interface {
	io.ReadWriteCloser

	// Fd returns its file descriptor
	Fd() uintptr

	// Name returns its file name.
	Name() string
}

File represents an input/output resource with a file descriptor.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL