iox

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 7 Imported by: 9 modules, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

iox

Go Reference Benchmarks Codecov

Non-blocking semantics for Go io package: first-class signals for would-block and multi-shot.

Language: English | 简体中文 | Español | 日本語 | Français

Overview

iox is for non-blocking I/O stacks where “wait for readiness before retrying” (ErrWouldBlock) and “keep observing the same operation” (ErrMore) are normal control flow.

Its copy and tee helpers use Go’s standard io.Reader and io.Writer interfaces. In the familiar (n, err) result, n reports bytes already transferred and err guides the caller’s next step. Either signal can accompany zero or more bytes, so account for n first.

I/O results

Error Classify result Caller action
nil OutcomeOK Continue or finish the transfer
ErrWouldBlock OutcomeWouldBlock Wait for readiness before retrying
ErrMore OutcomeMore Keep the operation active and observe the next completion
Other error OutcomeFailure Handle the error with the count already reported

On a direct Read, io.EOF marks the end of input. Process any final bytes before finishing. Passing io.EOF to Classify yields OutcomeFailure.

Installation and example

This module requires Go 1.27 or later.

go get code.hybscloud.com/iox

The second Copy transfers "world" before the reader reports ErrWouldBlock. The caller consumes those five bytes with CopyN, then uses its waitReadable function to wait for the source to become readable again. Readiness example

src := &reader{
	{data: "hello", err: iox.ErrMore},
	{data: "world"},
	{err: iox.ErrWouldBlock},
	{data: "iox"},
}
var dst bytes.Buffer

n, err := iox.Copy(&dst, src)
fmt.Printf("%d %v %q\n", n, err, dst.String()) // 5 io: expect more "hello"
_, _ = iox.CopyN(io.Discard, &dst, n)

if iox.Classify(err) == iox.OutcomeMore {
	n, err = iox.Copy(&dst, src)
	fmt.Printf("%d %v %q\n", n, err, dst.String()) // 5 io: would block "world"
	_, _ = iox.CopyN(io.Discard, &dst, n)
}

if iox.Classify(err) == iox.OutcomeWouldBlock {
	waitReadable()
	n, err = iox.Copy(&dst, src)
	fmt.Printf("%d %v %q\n", n, err, dst.String()) // 3 <nil> "iox"
}
return err

The reader keeps any bytes that do not fit in p. A zero-length read leaves the chunk untouched. The error is returned with the chunk’s last byte, or on its own for an empty chunk.

type reader []struct {
	data string
	err  error
}

func (r *reader) Read(p []byte) (int, error) {
	if len(p) == 0 {
		return 0, nil
	}
	if len(*r) == 0 {
		return 0, io.EOF
	}
	chunk := &(*r)[0]
	n := copy(p, chunk.data)
	if n < len(chunk.data) {
		chunk.data = chunk.data[n:]
		return n, nil
	}
	*r = (*r)[1:]
	return n, chunk.err
}

Canonical control loop

Callers should handle progress first, then classify control with the package helpers:

for {
	n, err := op()
	if n > 0 {
		consume(n)
	}

	switch {
	case err == nil:
		return nil
	case iox.IsWouldBlock(err):
		wait()
		continue
	case iox.IsMore(err):
		continue
	default:
		return err
	}
}

API overview

  • Errors

    • ErrWouldBlock, ErrMore, ErrNoSeeker
  • Copy

    • Copy(dst Writer, src Reader) (int64, error)
    • CopyBuffer(dst Writer, src Reader, buf []byte) (int64, error)
    • CopyN(dst Writer, src Reader, n int64) (int64, error)
    • CopyNBuffer(dst Writer, src Reader, n int64, buf []byte) (int64, error)
    • CopyPolicy, CopyBufferPolicy, CopyNPolicy, and CopyNBufferPolicy take a final SemanticPolicy argument.
  • Tee

    • TeeReader(r Reader, w Writer) Reader
    • TeeWriter(primary, tee Writer) Writer
    • TeeReaderPolicy and TeeWriterPolicy also take a final SemanticPolicy argument.
  • Adapters

    • AsWriterTo(r Reader) Reader (adds io.WriterTo via iox.Copy)
    • AsReaderFrom(w Writer) Writer (adds io.ReaderFrom via iox.Copy)
  • Semantics

    • Outcome
    • Classify(err error) Outcome
    • IsSemantic(err error) bool
    • IsNonFailure(err error) bool
    • IsFailure(err error) bool
    • IsWouldBlock(err error) bool
    • IsMore(err error) bool
    • IsProgress(err error) bool
  • Backoff

    • Backoff — adaptive back-off for external I/O waiting
    • DefaultBackoffBase (500µs), DefaultBackoffMax (100ms)

Resumable I/O

Step.Next returns a value, an error and a Wait. A zero wait means the step has finished. Finish supplies the terminal result. Await describes a wait for a typed value and a continuation that returns the next step.

Call Wait.Arm with the driver’s enqueue function. The trigger can signal before Arm returns. The first accepted Signal.Deliver enqueues one Ready. A worker can claim it once with TryResume to run the continuation. If Deliver returns false, the source keeps its value. Typed completion example

WriteStep records the count and error from each write. If the writer accepts only a prefix and returns ErrWouldBlock, a wake permits one attempt to write the suffix to the same writer. If the writer accepts the whole buffer, the step finishes with its error, including ErrWouldBlock. Keep the buffer valid and unmodified until completion or successful withdrawal.

Backoff — Adaptive Waiting for External I/O

When a readiness notification is available, wait for it after ErrWouldBlock. Otherwise, iox.Backoff.Wait sleeps the calling goroutine between attempts.

Three-Tier Progress Model:

Tier Mechanism Use Case
Strike System call Direct kernel hit
Spin Hardware yield (spin) Local atomic synchronization
Adapt Software backoff (iox.Backoff) External I/O readiness

Zero-value ready to use:

var b iox.Backoff // uses DefaultBackoffBase (500µs) and DefaultBackoffMax (100ms)

for {
	n, err := conn.Read(buf)
	if n > 0 {
		process(buf[:n])
		b.Reset() // reset on successful progress
	}
	if iox.IsWouldBlock(err) {
		b.Wait() // adaptive sleep with jitter
		continue
	}
	if err != nil || n == 0 {
		return err
	}
}

Process any bytes first. If the error matches ErrWouldBlock, the loop waits before retrying, even if it also matches ErrMore. The loop returns other errors unchanged. A (0, nil) read returns control to the caller and can occur before EOF.

Block n contains n retry intervals. Duration() reports the nominal interval, min(n × base, max). Jitter varies each interval by up to 12.5%, so it can exceed max.

  • NextDelay() advances the schedule once and returns the interval for a retry timer.
  • Wait() calls NextDelay() and sleeps the calling goroutine for that interval.
  • Reset() returns to block 1 and preserves the base and cap.
  • SetBase(d) and SetMax(d) accept positive durations and preserve the current block.

Tee semantics (counts and errors)

  • TeeReader returns n as the number of bytes read from r (source progress), even if the side write fails/is short.
  • TeeWriter returns n as the number of bytes accepted by primary (primary progress), even if the tee write fails/is short.
  • When n > 0, a tee adapter may return (n, err) where err comes from the side/tee (including ErrWouldBlock/ErrMore). Process p[:n] first.
  • For best interoperability with policy-driven helpers, return ErrWouldBlock/ErrMore as-is (avoid wrapping).

Semantic Policy

Some helpers accept an optional SemanticPolicy to decide what to do when they encounter ErrWouldBlock or ErrMore (e.g., return immediately vs yield and retry).

The default nil policy leaves waiting and retrying to the caller. For n > 0, CopyNPolicy and CopyNBufferPolicy return (n, nil) once the destination accepts all n bytes. They skip policy callbacks for a signal reported with the final byte.

Classification and exact sentinel dispatch

Classification helpers (IsMore, IsWouldBlock, IsSemantic, IsNonFailure, IsFailure, and Classify) use errors.Is, so wrapped semantic sentinels classify correctly at API boundaries and in diagnostics. Prefer these helpers over direct errors.Is calls when classifying iox semantic-control outcomes.

IsProgress is true only when Classify selects OutcomeOK or OutcomeMore. If an error matches both semantic sentinels, ErrWouldBlock takes precedence and IsProgress is false. IsMore and IsWouldBlock report sentinel membership, so both may be true for the same error. These predicates do not measure byte progress; always account for returned counts separately.

Copy and tee helpers consult the policy only for the exact ErrMore and ErrWouldBlock sentinels. Return these sentinels unwrapped when you want the policy to handle them.

Fast paths and semantic preservation

Copy prefers the source’s io.WriterTo, then the destination’s io.ReaderFrom. The generic loop uses the supplied buffer or a 32 KiB default. CopyN limits the source to the remaining byte count. It can use the destination’s ReadFrom and bypasses the original source’s WriteTo.

A delegated method reports the total bytes transferred and one error. Return ErrWouldBlock or ErrMore unwrapped so a policy can handle the signal. A method that supports retries must preserve any unwritten bytes. YieldOnWriteWouldBlockPolicy retries ErrWouldBlock from either method, even when a read produced it.

If you have a plain io.Reader/io.Writer but want the fast-path interfaces to exist and preserve semantics, wrap with:

  • iox.AsWriterTo(r) to add a WriteTo implemented via iox.Copy
  • iox.AsReaderFrom(w) to add a ReadFrom implemented via iox.Copy
Empty reads and bounded copies

In the generic read/write loop, Copy stops on a (0, nil) read and returns (written, nil). Such a read can occur before EOF. A delegated WriteTo or ReadFrom controls its own reads.

For a positive limit, CopyN and its variants return (n, nil) once the destination has accepted n bytes. An early EOF or a shorter copy ending with nil yields io.ErrUnexpectedEOF. The underlying multi-shot operation can remain active after the bounded copy finishes.

Partial writes

When the generic loop returns a semantic write error after a short write, it rewinds the unwritten suffix with seeker.Seek(int64(nw-nr), io.SeekCurrent). Here nr is the number of bytes read and nw the number accepted by the destination. A failed seek takes precedence over the write error. A source without io.Seeker yields ErrNoSeeker.

With CopyPolicy, PolicyRetry retains that suffix across retries of an exact ErrWouldBlock or ErrMore, including on non-seekable sources. A delegated WriteTo or ReadFrom owns its own source position and recovery.

Benchmarks

BenchmarkCopyBufferReuse compares iox.CopyBuffer, iox.CopyBufferPolicy with ReturnPolicy, and io.CopyBuffer on the generic read/write path. Each case reuses a 32 KiB buffer to copy the same in-memory input until EOF.

go test -run '^$' -bench '^BenchmarkCopyBufferReuse$' -benchmem -benchtime=200ms -count=10 -cpu=1 -timeout=120s .

Run both revisions on the same machine with the same Go version and similar load. Compare ns/op and allocs/op for matching input sizes. To measure wake-up latency, use a workload that waits for I/O readiness.

License

MIT — see LICENSE.

©2025 Hayabusa Cloud Co., Ltd.

Documentation

Overview

Package iox extends Go's io interfaces with signals for non-blocking and multi-shot I/O. Reader and Writer are aliases of the standard interfaces.

Process the returned byte count before handling the error. ErrWouldBlock means further progress requires readiness. ErrMore means the operation remains active and another observation is expected. Either signal can accompany zero or more bytes.

Classify and the error predicates recognize wrapped signals. If an error matches both sentinels, Classify selects OutcomeWouldBlock. IsProgress reports the OK and More outcomes. IsWouldBlock and IsMore test each sentinel independently. Copy and tee helpers consult their policies only for exact sentinels.

A Step holds a terminal result from Finish or a pending wait from Await. A driver registers the wait with Wait.Arm. Once a signal is accepted, a worker can claim the ready work with Ready.TryResume to run its continuation.

WriteStep retains the unwritten suffix after a partial ErrWouldBlock. A wake permits one more write to the same destination. A full count ends the operation with the writer's error and the total accepted byte count.

Copy uses WriterTo or ReaderFrom when available. A delegated method owns source advancement and recovery from partial writes. In the generic read/write loop, a (0, nil) read ends the copy and returns (written, nil). CopyN and its variants return success once the destination accepts the requested number of bytes, even if the underlying operation remains active.

Index

Examples

Constants

View Source
const (
	// DefaultBackoffBase is the initial sleep duration before jitter.
	DefaultBackoffBase = 500 * time.Microsecond

	// DefaultBackoffMax is the default duration cap before jitter (100ms).
	DefaultBackoffMax = 100 * time.Millisecond
)

Variables

View Source
var (
	// EOF is returned by Read when no more input is available.
	// Functions should return EOF only to signal a graceful end of input.
	EOF = io.EOF

	// ErrClosedPipe is returned on write to a closed pipe.
	// It may also be returned by other operations that behave like a closed pipe.
	ErrClosedPipe = io.ErrClosedPipe

	// ErrNoProgress reports that a Reader returned no data and no error after
	// multiple Read calls. It is used by some io helpers to detect broken Readers
	// (i.e., lack of forward progress).
	ErrNoProgress = io.ErrNoProgress

	// ErrShortBuffer means a provided buffer was too small to complete the operation.
	// Callers typically retry with a larger buffer.
	ErrShortBuffer = io.ErrShortBuffer

	// ErrShortWrite means a write accepted fewer bytes than requested and returned
	// no explicit error (or equivalently, could not complete the full write).
	ErrShortWrite = io.ErrShortWrite

	// ErrUnexpectedEOF means EOF was encountered earlier than expected.
	// It is commonly used by fixed-size reads/copies when the stream ends mid-record.
	ErrUnexpectedEOF = io.ErrUnexpectedEOF
)

Common sentinel errors re-exported for convenience.

Note: iox also defines semantic non-failure errors (ErrWouldBlock, ErrMore) used by iox helpers and adapters; those are not part of the standard io set.

View Source
var ErrMore = errors.New("io: expect more")

ErrMore signals that the operation remains active. Process any bytes already transferred and continue observing the operation.

View Source
var ErrNoSeeker = errors.New("io: source is not seekable; partial write unrecoverable")

ErrNoSeeker means the generic copy loop could not rewind a non-seekable source after a partial write with a semantic error. The source has already advanced past the unwritten bytes. To keep the suffix on a non-seekable source, use CopyPolicy from the start and select PolicyRetry when the write returns an exact ErrWouldBlock or ErrMore.

View Source
var ErrWaitUnavailable = errors.New("iox: wait unavailable")

ErrWaitUnavailable means the handle is stale, withdrawn or already armed.

View Source
var ErrWouldBlock = errors.New("io: would block")

ErrWouldBlock signals that further progress requires readiness. Process any bytes already transferred before waiting to retry.

View Source
var ErrWriteAttemptExhausted = errors.New("iox: write attempt number exhausted")

ErrWriteAttemptExhausted means a write needs another wait after using the largest attempt number for its demand.

Functions

func Copy

func Copy(dst Writer, src Reader) (written int64, err error)

Copy copies from src to dst and returns the number of bytes written. ErrWouldBlock and ErrMore can accompany partial progress.

A WriterTo source takes precedence over a ReaderFrom destination. The selected method owns its progress and partial-write recovery. Otherwise Copy uses a read/write loop and stops on a (0, nil) read. An io.EOF from Read or a delegated method ends a successful copy. Copy returns an io.EOF from a direct Write to the caller.

If a generic write accepts only part of a read and returns a semantic error, Copy rewinds the unwritten suffix on a Seeker. It returns the seek error if rewinding fails, or ErrNoSeeker if src cannot seek.

func CopyBuffer

func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

CopyBuffer is Copy with caller-supplied scratch space for the generic loop. A nil buf selects the default Buffer. A non-nil, empty buf panics. WriterTo and ReaderFrom perform their own buffering.

func CopyBufferPolicy added in v0.2.0

func CopyBufferPolicy(dst Writer, src Reader, buf []byte, policy SemanticPolicy) (written int64, err error)

CopyBufferPolicy is CopyPolicy with the buffer rules of CopyBuffer. A nil policy uses CopyBuffer.

func CopyN

func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

CopyN copies n bytes from src to dst. For n <= 0 it returns (0, nil). For n > 0 it returns (n, nil) once the destination has accepted n bytes. An early EOF or a short copy with nil error returns ErrUnexpectedEOF. Other errors can accompany the number of bytes already written.

CopyN limits reads to the remaining byte count. It can delegate to ReaderFrom on dst. Otherwise it uses Copy's generic loop and partial-write recovery. After a recoverable interruption, resume with n-written bytes.

func CopyNBuffer

func CopyNBuffer(dst Writer, src Reader, n int64, buf []byte) (written int64, err error)

CopyNBuffer is CopyN with scratch space for the generic loop. A nil buf selects the default Buffer. For n > 0, a non-nil, empty buf panics.

func CopyNBufferPolicy added in v0.2.0

func CopyNBufferPolicy(dst Writer, src Reader, n int64, buf []byte, policy SemanticPolicy) (written int64, err error)

CopyNBufferPolicy is CopyNPolicy with the buffer rules of CopyNBuffer. A nil policy uses CopyNBuffer.

func CopyNPolicy added in v0.2.0

func CopyNPolicy(dst Writer, src Reader, n int64, policy SemanticPolicy) (written int64, err error)

CopyNPolicy is CopyN with a policy for exact semantic signals while bytes remain. It skips policy callbacks for a signal received with the final requested byte. A nil policy uses CopyN.

func CopyPolicy added in v0.2.0

func CopyPolicy(dst Writer, src Reader, policy SemanticPolicy) (written int64, err error)

CopyPolicy is Copy with a policy for exact ErrWouldBlock and ErrMore signals. A nil policy uses Copy. PolicyRetry calls Yield before resuming.

On a partial write, the generic loop retains the unwritten suffix across retries. Returning the signal uses Copy's seek recovery. For a delegated WriterTo or ReaderFrom, the policy receives the Op for that method. A retry calls the method again, so it must preserve any unwritten bytes.

func IsFailure added in v0.3.6

func IsFailure(err error) bool

IsFailure reports whether err is an actual failure rather than nil or an iox semantic control signal.

func IsMore

func IsMore(err error) bool

IsMore reports whether err carries the iox multi-shot (more completions) semantic. It returns true for ErrMore and wrappers (via errors.Is).

func IsNonFailure

func IsNonFailure(err error) bool

IsNonFailure reports whether err should be treated as a non-failure in non-blocking I/O control flow: nil, ErrWouldBlock, or ErrMore.

Typical usage: decide whether to keep a descriptor active without logging an error or tearing down the operation.

func IsProgress

func IsProgress(err error) bool

IsProgress reports whether Classify selects OutcomeOK or OutcomeMore. Use the returned byte count to determine how much data moved.

func IsSemantic

func IsSemantic(err error) bool

IsSemantic reports whether err represents an iox semantic signal: either ErrWouldBlock or ErrMore (including wrapped forms).

func IsWouldBlock

func IsWouldBlock(err error) bool

IsWouldBlock reports whether err carries the iox would-block semantic. It returns true for ErrWouldBlock and wrappers (via errors.Is).

Types

type Backoff added in v0.3.0

type Backoff struct {
	// contains filtered or unexported fields
}

Backoff spaces retry attempts when progress depends on external I/O. Its zero value uses DefaultBackoffBase and DefaultBackoffMax. Use one Backoff per retry loop, or synchronize access to a shared Backoff.

Block n supplies n intervals of min(n × base, max) with up to 12.5% jitter. Backoff.Wait and Backoff.NextDelay each consume one interval. Call Backoff.Reset after progress to start again at block 1.

func (*Backoff) Block added in v0.3.0

func (b *Backoff) Block() int

Block returns the current block number, starting at 1.

func (*Backoff) Duration added in v0.3.0

func (b *Backoff) Duration() time.Duration

Duration reports the current block's interval before jitter without advancing the schedule. For a zero-value Backoff it returns DefaultBackoffBase.

func (*Backoff) NextDelay added in v0.4.0

func (b *Backoff) NextDelay() time.Duration

NextDelay returns the next jittered interval and advances the schedule without sleeping. A caller can use the interval to arm a retry timer. The cap applies before jitter. The result saturates at the largest time.Duration.

func (*Backoff) Reset added in v0.3.0

func (b *Backoff) Reset()

Reset restarts the block schedule and preserves the configured base and cap.

func (*Backoff) SetBase added in v0.3.0

func (b *Backoff) SetBase(d time.Duration)

SetBase configures the initial duration and linear scaling factor. d must be positive. The current block is preserved.

func (*Backoff) SetMax added in v0.3.0

func (b *Backoff) SetMax(d time.Duration)

SetMax configures the duration cap before jitter. d must be positive. The current block is preserved.

func (*Backoff) Wait added in v0.3.0

func (b *Backoff) Wait()

Wait sleeps the calling goroutine for one interval from Backoff.NextDelay.

type Buffer

type Buffer [32 * 1024]byte

Buffer is the default fixed-size buffer type used by Copy when none is supplied.

type ByteReader

type ByteReader = io.ByteReader

ByteReader reads and returns a single byte.

ByteReader is an alias of io.ByteReader.

type ByteScanner

type ByteScanner = io.ByteScanner

ByteScanner is a ByteReader that can "unread" the last byte read.

ByteScanner is an alias of io.ByteScanner.

type ByteWriter

type ByteWriter = io.ByteWriter

ByteWriter writes a single byte.

ByteWriter is an alias of io.ByteWriter.

type Closer

type Closer = io.Closer

Closer is an alias of io.Closer. The behavior of repeated calls to Close is unspecified unless the implementation documents it.

type Observation added in v0.4.0

type Observation struct {
	N   int64
	Err error
}

Observation is the count and original error from one I/O call.

type Op added in v0.2.0

type Op uint8

Op identifies the call that reported a semantic signal. Direct reads and writes have distinct values. OpCopyWriterTo and OpCopyReaderFrom identify a delegated method whose signal can come from either side.

const (
	OpCopyRead Op = iota
	OpCopyWrite

	OpCopyWriterTo
	OpCopyReaderFrom

	OpTeeReaderRead
	OpTeeReaderSideWrite

	OpTeeWriterPrimaryWrite
	OpTeeWriterTeeWrite
)

func (Op) String added in v0.2.0

func (op Op) String() string

type Outcome

type Outcome uint8

Outcome classifies the error returned by an I/O operation. Treat the constants as unordered labels in a switch. The byte count reports progress.

const (
	// OutcomeFailure denotes an error other than a semantic signal.
	OutcomeFailure Outcome = iota
	// OutcomeOK denotes a nil error.
	OutcomeOK
	// OutcomeWouldBlock means further progress requires readiness.
	OutcomeWouldBlock
	// OutcomeMore means the operation remains active.
	OutcomeMore
)

func Classify

func Classify(err error) Outcome

Classify returns OutcomeOK for nil, OutcomeWouldBlock for errors matching ErrWouldBlock, OutcomeMore for errors matching ErrMore, and OutcomeFailure otherwise. ErrWouldBlock takes precedence if both match. Classify treats EOF as OutcomeFailure. Copy helpers handle EOF separately.

func (Outcome) String

func (o Outcome) String() string

type PolicyAction added in v0.2.0

type PolicyAction uint8

PolicyAction tells an engine whether it should return to the caller or attempt the operation again.

const (
	// PolicyReturn tells the helper to return control to the caller.
	PolicyReturn PolicyAction = iota

	// PolicyRetry tells the helper to call Yield before continuing.
	PolicyRetry
)

type PolicyFunc added in v0.2.0

type PolicyFunc struct {
	YieldFunc      func(op Op)
	WouldBlockFunc func(op Op) PolicyAction
	MoreFunc       func(op Op) PolicyAction
}

PolicyFunc is a convenience implementation for callers that want to inject behavior without defining a struct type.

Default behaviors when fields are nil:

  • YieldFunc: calls runtime.Gosched() to yield the processor
  • WouldBlockFunc: returns PolicyReturn (caller handles ErrWouldBlock)
  • MoreFunc: returns PolicyReturn (caller handles ErrMore)

func (PolicyFunc) OnMore added in v0.2.0

func (p PolicyFunc) OnMore(op Op) PolicyAction

func (PolicyFunc) OnWouldBlock added in v0.2.0

func (p PolicyFunc) OnWouldBlock(op Op) PolicyAction

func (PolicyFunc) Yield added in v0.2.0

func (p PolicyFunc) Yield(op Op)

type ReadCloser

type ReadCloser = io.ReadCloser

ReadCloser groups Read and Close.

ReadCloser is an alias of io.ReadCloser.

type ReadSeeker

type ReadSeeker = io.ReadSeeker

ReadSeeker groups Read and Seek.

ReadSeeker is an alias of io.ReadSeeker.

type ReadWriteCloser

type ReadWriteCloser = io.ReadWriteCloser

ReadWriteCloser groups Read, Write, and Close.

ReadWriteCloser is an alias of io.ReadWriteCloser.

type ReadWriteSeeker

type ReadWriteSeeker = io.ReadWriteSeeker

ReadWriteSeeker groups Read, Write, and Seek.

ReadWriteSeeker is an alias of io.ReadWriteSeeker.

type ReadWriter

type ReadWriter = io.ReadWriter

ReadWriter groups the basic Read and Write methods.

ReadWriter is an alias of io.ReadWriter.

type Reader

type Reader = io.Reader

Reader is implemented by types that can read bytes into p.

Read must return the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n > 0, it may return a non-nil error to signal a condition observed after producing those bytes.

Callers should treat a return of (0, nil) as "no progress": it does not mean end-of-stream. Well-behaved implementations should avoid returning (0, nil) except when len(p) == 0.

Reader is an alias of io.Reader.

func AsWriterTo

func AsWriterTo(r Reader) Reader

AsWriterTo wraps r so that it also implements WriterTo via iox semantics.

func TeeReader

func TeeReader(r Reader, w Writer) Reader

TeeReader returns a Reader that mirrors bytes read from r to w. Read returns the count from r, even if w accepts fewer bytes. A side-write error takes precedence over the read error. A short side write with nil error returns ErrShortWrite.

func TeeReaderPolicy added in v0.2.0

func TeeReaderPolicy(r Reader, w Writer, policy SemanticPolicy) Reader

TeeReaderPolicy is TeeReader with a policy for exact semantic signals. A nil policy uses TeeReader. On PolicyRetry, a side write resumes with its unwritten suffix. For a read signal, the helper yields and returns (n, nil) if it has data to deliver, or retries the read if n is zero.

type ReaderAt

type ReaderAt = io.ReaderAt

ReaderAt reads from the underlying input at a given offset.

ReaderAt should not affect and should not be affected by the current seek offset. Implementations must return a non-nil error when n < len(p).

ReaderAt is an alias of io.ReaderAt.

type ReaderFrom

type ReaderFrom = io.ReaderFrom

ReaderFrom is an optional optimization for Writers.

If implemented by a Writer, Copy-like helpers may call ReadFrom to transfer data from r more efficiently than a generic read/write loop.

ReaderFrom is an alias of io.ReaderFrom.

type ReaderFromAdapter

type ReaderFromAdapter struct{ W Writer }

ReaderFromAdapter adapts a Writer to implement ReaderFrom using iox.Copy.

func (ReaderFromAdapter) ReadFrom

func (a ReaderFromAdapter) ReadFrom(src Reader) (int64, error)

ReadFrom delegates to iox.Copy to preserve extended semantics.

func (ReaderFromAdapter) Write

func (a ReaderFromAdapter) Write(p []byte) (int, error)

Write forwards to the underlying Writer to preserve Writer semantics.

type Ready added in v0.4.0

type Ready[A any] struct {
	// contains filtered or unexported fields
}

Ready carries one accepted signal to a worker. Copies share a single claim.

func (Ready[A]) TryResume added in v0.4.0

func (r Ready[A]) TryResume() (Step[A], bool)

TryResume consumes the evidence and runs the continuation on the calling goroutine. A zero, stale or already consumed ready value returns false.

type ReturnPolicy added in v0.2.0

type ReturnPolicy struct{}

ReturnPolicy is the simplest policy: never waits and never retries. It preserves non-blocking semantics (callers handle ErrWouldBlock/ErrMore).

func (ReturnPolicy) OnMore added in v0.2.0

func (ReturnPolicy) OnMore(Op) PolicyAction

func (ReturnPolicy) OnWouldBlock added in v0.2.0

func (ReturnPolicy) OnWouldBlock(Op) PolicyAction

func (ReturnPolicy) Yield added in v0.2.0

func (ReturnPolicy) Yield(Op)

type RuneReader

type RuneReader = io.RuneReader

RuneReader reads and returns a single UTF-8 encoded rune.

RuneReader is an alias of io.RuneReader.

type RuneScanner

type RuneScanner = io.RuneScanner

RuneScanner is a RuneReader that can "unread" the last rune read.

RuneScanner is an alias of io.RuneScanner.

type Seeker

type Seeker = io.Seeker

Seeker is implemented by types that can set the offset for the next Read or Write.

Seek sets the offset based on whence and returns the new absolute offset.

Seeker is an alias of io.Seeker.

type SemanticPolicy added in v0.2.0

type SemanticPolicy interface {
	Yield(op Op)
	OnWouldBlock(op Op) PolicyAction
	OnMore(op Op) PolicyAction
}

SemanticPolicy selects an action for an exact ErrWouldBlock or ErrMore. PolicyRetry invokes Yield before the helper resumes. Yield can wait for readiness. Repeated retries without a readiness wait can spin.

A bounded copy skips the policy once its byte count is complete. TeeReaderPolicy can yield and return data already read to its caller.

type Signal added in v0.4.0

type Signal[X any] struct {
	// contains filtered or unexported fields
}

Signal delivers evidence for one registration. Copies can be used concurrently. A zero or stale signal rejects delivery.

func (Signal[X]) Deliver added in v0.4.0

func (s Signal[X]) Deliver(value X) bool

Deliver offers value to the waiting operation. The first matching delivery transfers ownership, calls enqueue, and returns true. On false the source still owns value. A readiness or timer source can supply struct{} as permission for one probe.

type Step added in v0.4.0

type Step[A any] struct {
	// contains filtered or unexported fields
}

Step describes the result of advancing an operation to its next boundary. The zero Step finishes with the zero value of A and a nil error.

func Await added in v0.4.0

func Await[X, A any](ticket Ticket, trigger Trigger[X], resume func(X) Step[A]) Step[A]

Await returns a step waiting for typed evidence. Wait.Arm registers trigger, and the worker that claims Ready.TryResume runs resume. Both trigger and resume must be non-nil. Use WaitSlot.Await to reuse storage across successive attempts.

Example
// ©Hayabusa Cloud Co., Ltd. 2026. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"

	"code.hybscloud.com/iox"
)

// The source remembers where to deliver the next frame for this demand.
type frameSource struct{ next iox.Signal[[]byte] }

func (f *frameSource) Arm(_ iox.Ticket, next iox.Signal[[]byte]) error {
	f.next = next
	return nil
}

func main() {
	var source frameSource
	step := iox.Await(iox.Ticket{Demand: 1}, &source, func(frame []byte) iox.Step[int] {
		return iox.Finish(len(frame), nil)
	})
	_, _, wait := step.Next()

	queue := make(chan iox.Ready[int], 1)
	if err := wait.Arm(func(r iox.Ready[int]) { queue <- r }); err != nil {
		panic(err)
	}
	// An empty frame arrives. The driver dispatches the work on a later turn.
	if !source.next.Deliver([]byte{}) {
		return
	}
	if next, ok := (<-queue).TryResume(); ok {
		size, err, _ := next.Next()
		fmt.Println(size, err)
	}
}
Output:
0 <nil>

func Finish added in v0.4.0

func Finish[A any](value A, err error) Step[A]

Finish returns a terminal step. The value may include progress on failure.

func WriteStep added in v0.4.0

func WriteStep(dst Writer, p []byte, ticket Ticket, writable Trigger[struct{}]) Step[int64]

WriteStep calls dst.Write once, including for an empty p. Use a nonblocking writer when driving the operation from an event loop. If dst accepts fewer than len(p) bytes and returns ErrWouldBlock (possibly wrapped), a signal from writable permits one write of the remaining suffix to dst. Supply a trigger when dst can block. Keep p valid and unmodified until the operation finishes or Wait.Withdraw succeeds.

Each observation records the count and original error from one call. The terminal result reports the total accepted bytes. A full count ends the operation with the writer's error, even if it is ErrWouldBlock. On an incomplete write, other errors, including ErrMore, are returned as received. A short nil-error write returns ErrShortWrite.

The first wait uses ticket. Each subsequent wait increments ticket.Attempt. A probe at the largest attempt number can still complete the write. If it needs another wait, the operation finishes with ErrWriteAttemptExhausted.

func (Step[A]) Next added in v0.4.0

func (s Step[A]) Next() (value A, err error, wait Wait[A])

Next returns the terminal value and error when wait.IsZero(). Otherwise wait identifies the outstanding work. Copies refer to the same single-use attempt even if the operation later reuses its storage.

func (Step[A]) Observation added in v0.4.0

func (s Step[A]) Observation() (Observation, bool)

Observation reports the recorded call, including an actual (0, nil). A step that only registers or schedules work can have no observation.

func (Step[A]) WithObservation added in v0.4.0

func (s Step[A]) WithObservation(o Observation) Step[A]

WithObservation returns a copy recording an actual I/O call. It panics if the step already records a call. Construct a separate step for each call.

type StringWriter

type StringWriter = io.StringWriter

StringWriter writes the contents of s more efficiently than Write([]byte(s)) for implementations that can avoid an allocation/copy.

StringWriter is an alias of io.StringWriter.

type Ticket added in v0.4.0

type Ticket struct {
	Demand  uint64
	Attempt uint64
}

Ticket identifies one wait attempt for a demand. A worker handoff carries the same ticket. Give each new attempt a fresh identity at its source.

type Trigger added in v0.4.0

type Trigger[X any] interface {
	Arm(Ticket, Signal[X]) error
}

Trigger registers the event that supplies the evidence for one wait. Arm must cover events arriving during registration, for example by registering and rechecking readiness. It may signal before returning. Return an error only when the source accepted neither registration nor evidence. The source owns cancellation, routing and disposal of unaccepted evidence.

type Wait added in v0.4.0

type Wait[A any] struct {
	// contains filtered or unexported fields
}

Wait is a handle to one pending attempt. Its ticket and identity survive transfer to another worker.

func (Wait[A]) Arm added in v0.4.0

func (w Wait[A]) Arm(enqueue func(Ready[A])) error

Arm registers this wait. enqueue must be non-nil and accept the ready value on the signaling goroutine. It can run before Arm returns. Once registration starts, Arm returns the trigger's result, even if another goroutine withdraws the wait. A refused wait can be armed again while it is still pending. A call that cannot claim the pending wait returns ErrWaitUnavailable.

func (Wait[A]) IsZero added in v0.4.0

func (w Wait[A]) IsZero() bool

IsZero reports whether this handle describes no wait. A copied handle keeps its identity after its attempt has been consumed or withdrawn.

func (Wait[A]) Ticket added in v0.4.0

func (w Wait[A]) Ticket() Ticket

Ticket returns the demand and attempt supplied to Await.

func (Wait[A]) Withdraw added in v0.4.0

func (w Wait[A]) Withdraw() bool

Withdraw releases the wait if no signal has been accepted. On false the handle is stale or the queued work already owns the evidence. The binding remains responsible for its external registration and resources, even if registration finishes after withdrawal.

type WaitSlot added in v0.4.0

type WaitSlot[X, A any] struct {
	// contains filtered or unexported fields
}

WaitSlot holds one outstanding wait. Its zero value is ready for use. It must not be copied after first use. A slot can be reused from inside its continuation or after a successful withdrawal. Each wait and arm uses one of 2⁶¹ generations. Retire the slot before reusing a live generation.

func (*WaitSlot[X, A]) Await added in v0.4.0

func (s *WaitSlot[X, A]) Await(ticket Ticket, trigger Trigger[X], resume func(X) Step[A]) Step[A]

Await installs a new attempt in the slot. It panics if the previous attempt still owns the slot. trigger and resume must be non-nil.

type WriteCloser

type WriteCloser = io.WriteCloser

WriteCloser groups Write and Close.

WriteCloser is an alias of io.WriteCloser.

type WriteSeeker

type WriteSeeker = io.WriteSeeker

WriteSeeker groups Write and Seek.

WriteSeeker is an alias of io.WriteSeeker.

type Writer

type Writer = io.Writer

Writer is implemented by types that can write bytes from p.

Write returns the number of bytes accepted (0 <= n <= len(p)) and any error encountered. A short write (n < len(p)) must return a non-nil error.

Writer is an alias of io.Writer.

func AsReaderFrom

func AsReaderFrom(w Writer) Writer

AsReaderFrom wraps w so that it also implements ReaderFrom via iox semantics.

func TeeWriter

func TeeWriter(primary Writer, tee Writer) Writer

TeeWriter returns a Writer that writes to primary, then mirrors the accepted prefix to tee. Write returns the primary count even if the mirror fails. A short write with nil error counts as ErrShortWrite. A mirror error takes precedence over the primary result.

Resume at p[n:] to avoid duplicating primary writes. Any missing bytes from the mirrored prefix need separate recovery.

func TeeWriterPolicy added in v0.2.0

func TeeWriterPolicy(primary Writer, tee Writer, policy SemanticPolicy) Writer

TeeWriterPolicy is TeeWriter with a policy for exact semantic signals. On PolicyRetry it yields and resumes the interrupted write with its remaining bytes. An empty write reaches primary and can also be retried. A nil policy uses TeeWriter.

type WriterAt

type WriterAt = io.WriterAt

WriterAt writes to the underlying output at a given offset.

WriterAt should not affect and should not be affected by the current seek offset. Implementations must return a non-nil error when n < len(p).

WriterAt is an alias of io.WriterAt.

type WriterTo

type WriterTo = io.WriterTo

WriterTo is an optional optimization for Readers.

If implemented by a Reader, Copy-like helpers may call WriteTo to transfer data to w more efficiently than a generic read/write loop.

WriterTo is an alias of io.WriterTo.

type WriterToAdapter

type WriterToAdapter struct{ R Reader }

WriterToAdapter adapts a Reader to implement WriterTo using iox.Copy.

func (WriterToAdapter) Read

func (a WriterToAdapter) Read(p []byte) (int, error)

Read forwards to the underlying Reader to preserve Reader semantics.

func (WriterToAdapter) WriteTo

func (a WriterToAdapter) WriteTo(dst Writer) (int64, error)

WriteTo delegates to iox.Copy to preserve extended semantics.

type YieldOnWriteWouldBlockPolicy added in v0.2.0

type YieldOnWriteWouldBlockPolicy struct {
	YieldFunc func(op Op)
}

YieldOnWriteWouldBlockPolicy retries ErrWouldBlock from writes and from delegated WriterTo and ReaderFrom calls. Those methods report one aggregate error, which can originate on either side of the transfer. Direct reads and ErrMore return control to the caller.

func (YieldOnWriteWouldBlockPolicy) OnMore added in v0.2.0

func (YieldOnWriteWouldBlockPolicy) OnWouldBlock added in v0.2.0

func (YieldOnWriteWouldBlockPolicy) OnWouldBlock(op Op) PolicyAction

func (YieldOnWriteWouldBlockPolicy) Yield added in v0.2.0

func (p YieldOnWriteWouldBlockPolicy) Yield(op Op)

type YieldPolicy added in v0.2.0

type YieldPolicy struct {
	// YieldFunc is invoked when the engine decides to retry after ErrWouldBlock.
	// It may spin, park, poll, run an event-loop tick, etc.
	YieldFunc func(op Op)
}

YieldPolicy is a ready-to-use policy with the common mapping:

  • ErrWouldBlock: yield/wait and retry
  • ErrMore: return immediately (treat as a delivery/boundary signal)

This matches protocols where writer-side ErrMore denotes a completed frame and the caller wants to handle the boundary immediately, then call Copy again.

Default Yield behavior: runtime.Gosched().

func (YieldPolicy) OnMore added in v0.2.0

func (YieldPolicy) OnMore(Op) PolicyAction

func (YieldPolicy) OnWouldBlock added in v0.2.0

func (YieldPolicy) OnWouldBlock(Op) PolicyAction

func (YieldPolicy) Yield added in v0.2.0

func (p YieldPolicy) Yield(op Op)

Directories

Path Synopsis
Package examples demonstrates how copies report data, readiness, and multi-shot completions.
Package examples demonstrates how copies report data, readiness, and multi-shot completions.

Jump to

Keyboard shortcuts

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