Expand description
Host-driven, completion-shaped I/O. No background thread turns the loop.
The host owns the thread and decides when to collect completions. Optional process-wide blocking, signal and external-wait services start only on use.
use std::time::Duration;
use turnloop::{Completions, Config, Loop, OpResult, Timeout, Token};
let mut driver = Loop::new(Config::default())?;
let deadline = driver.now() + Duration::from_millis(2);
let timer = driver.timer(deadline, None, Token(42))?;
let mut completions = Completions::default();
loop {
driver.turn(Timeout::Until(deadline), &mut completions)?;
if completions.iter().any(|c| c.token == Token(42) && matches!(c.result, OpResult::Timer)) {
break;
}
}
// Run host callbacks only after turn has returned.
driver.close(timer, Token(43))?;
driver.turn(Timeout::Now, &mut completions)?;
assert!(!driver.alive());Blocking work declares how long it will hold its worker. Occupancy::Bounded
is the fixed, queued, backpressured set that short CPU-bound jobs belong on;
Occupancy::Long is a separately accounted, on-demand set for work that holds
a thread for a connection’s lifetime. Neither class can exhaust the other, and
pool_stats reports both without taking a lock.
Enable the executor feature for executor::LocalExecutor and futures-io
adapters. Each loop/executor belongs to its creating thread; its notifier and
poster may be cloned onto other threads.
Re-exports§
pub use backend::unix::Detached;
Modules§
- backend
- Internal platform contract, revision 2 (empty-wait instrumentation and native services).
Structs§
- Accept
Defaults - Options a listener applies to every connection it accepts.
- Access
Mode access(2)checks. All false tests existence only.- BufLease
- Owns the buffer until explicitly dropped/released. May safely survive turns. Keeping all leases applies backpressure; it never allocates a new pool buffer.
- Buffer
Pool - Fixed reusable read storage; leases return buffers when explicitly released or dropped.
- Cancellation
- The cooperative stop signal of a running pool job.
- ChildFd
- One additional child descriptor beyond stdin, stdout and stderr.
- Completion
- One host-visible operation result, carrying its original routing token.
- Completions
- Fixed-capacity output. Each turn clears old completions and fills at most this capacity. Retained completions remain in the driver, providing backpressure.
- Config
- Fixed loop capacities and shared blocking-pool configuration.
- DirEntries
- Iterate
(type, name)directory records from aFsResult::Directorypage. Names are native bytes on Unix, WTF-8 on Windows and UTF-8 on WASI. - DnsRequest
- Owned hostname and port for a pool-backed native address lookup.
- Driver
- A driver belongs to its constructing thread. Backend is an internal extension point used by platform lanes and the common contract suite.
- Error
- Portable error kind with an optional original operating-system code.
- Exit
Status - Child termination status, preserving exit codes and signal termination.
- File
Metadata - Metadata for Node
StatsandwatchFilesnapshots. A field the platform does not report is None; values are never invented. Windowsmodefollows libuv’s attribute mapping: type bits plus 0o666, or 0o444 when read-only. - File
Options - Open options covering Node’s string and numeric open flags.
- File
Time - Wall-clock timestamp relative to the Unix epoch, with nanoseconds retained.
- FsPath
- A validated, prepared pathname. Preparing converts once; cloning never allocates.
- Handle
- Loop-scoped generational identity; stale or foreign IDs never address a reused resource.
- Instant
- A measurement of a monotonically nondecreasing clock.
Opaque and useful only with
Duration. - IoBuf
- A stable, initialized, immutable byte region. Does not own the memory.
- IoBuf
Mut - A stable, exclusively writable region. Does not own the memory.
- Keep
Alive - TCP keep-alive probe schedule. Each
Nonekeeps the platform default. - Listen
Opts - Listener backlog, kernel reuse-port configuration and accepted-socket defaults.
- Metadata
- Metadata result held in reusable per-loop storage; dereferences to
FileMetadata. Dropping it returns the storage, so steady-statestatrequests allocate nothing once the loop has served one. Copy the value out to keep it beyond the completion. - Multicast
Group - A multicast group and the local interface that should carry it.
- Notifier
- Thread-safe, cloneable wake endpoint using the loop parking handshake.
- OpId
- Loop-scoped generational identity; stale or foreign IDs never address a reused resource.
- Pipe
Name - Local IPC address: a filesystem socket path on Unix or named-pipe name on Windows. Unix callers own removal of the socket path after closing the listener.
- Pool
Config - Configuration fixed by the first process-wide blocking-pool submission.
- Pool
Stats - A snapshot of the process-wide pool, as it looked at some point during the call (issue #44).
- Post
Error - Posting failure with ownership returned only when the payload was not accepted.
- Poster
- Bounded thread-safe payload queue routed to exactly one owning loop.
- Process
- Owned child identity and optional parent pipe handles, all belonging to one loop.
- Process
Spec - Child launch options. Arguments exclude
argv[0], which is the program name. Environment entries override inherited values unlessenv_clearis true. - TcpOpts
- Connect-time options for
Loop::tcp_connect. - Token
- Opaque host routing value, returned unchanged with its completions.
- Turn
Info - Completed turn statistics and current reference-counted liveness.
- UdpOpts
- UDP binding options. Reuse is bind-time only and stays here, not in
SocketOption; everything changeable on a live socket is an option. - Wait
Condition - Shared host wait condition. Hosts may provide their own atomic storage and call
notifyafter changing it. No predicate callback runs inside a loop turn. - Watch
Events - Iterate
(kind, name)records of anOpResult::Watchbatch, in native order. Names are relative to the watched directory using native separators; an event on the watched root (or a watched file) carries the root’s final component. - Watch
Options - Filesystem watch options.
- Window
Size - Terminal dimensions in character cells.
- Write
Vectored - Up to MAX_IOV owned or provided segments stored inline.
Enums§
- Child
FdSource - Child-side configuration of one extra descriptor.
- Error
Kind - Portable error categories independent of native numeric error codes.
- File
Type - Native file type; also the record tag of directory entries.
- FsRequest
- One typed request, submitted with
Loop::fs. Operations on the same handle run FIFO. A cancelled mutation that already started is not rolled back. - FsResult
- Successful typed results. Failures use
OpResult::Err. - FsTarget
- A metadata operation’s subject: a path or an open handle.
- Integration
- The fd/event is borrowed from the driver; it must never be closed by the host.
- Occupancy
- How long a submitted job will hold the worker thread that runs it.
- OpResult
- Host-visible I/O, timer, process, service and lifecycle results.
- Open
- Backend-neutral resource creation requests; unsupported kinds must fail explicitly.
- Payload
- Common small posts need no box/allocation. Larger host results can own bytes or a Send Rust value; the driver never invokes a function from this payload.
- Process
Stdio - Child-side standard-stream configuration.
- RawTransport
- The native identity of a transport, for host reporting and for a descriptor the host has taken ownership of (DESIGN §5a).
- ReadBuf
- Choose host-provided memory or an explicitly released pool lease for a read.
- Reuse
Port - What a second bind of the same address is allowed to do.
- Signal
- Portable signal names. Unsupported mappings return an error.
- Socket
Option - A socket option that can be changed after the socket exists.
- Socket
Option Kind - Names a readable socket option for
Loop::get_option. - Stdio
- Standard stream to duplicate into a loop. Closing it does not close the host fd.
- Symlink
Kind - Windows symbolic-link flavour; ignored elsewhere.
- Time
Change - Timestamp update for
SetTimes. - Timeout
- Exact timeout budget for one host-driven turn.
- TtyMode
- Terminal input/output mode, restored when the owning handle closes or drops.
- Wait
Result - Why an external wait completed.
- Watch
Kind - Node
fs.watchevent type. - Write
Buf - Stable write data, either borrowed under an unsafe lifetime contract or owned.
Constants§
- BACKEND_
NAME - Backend selected from the compilation target, independently of Cargo features.
- MAX_
CHILD_ FD - Highest child descriptor number an extra
ChildFdmay use. - MAX_IOV
- Fixed upper bound keeps writev descriptors inline in the operation table.
- RECORD_
HEADER - Size of a record header: tag, reserved zero, little-endian u16 name length.
Functions§
- pool_
stats - Read the process-wide pool’s
PoolStats. Never blocks and never fails; reports zeros before the first submission has started the pool.
Type Aliases§
- Blocking
Result - Result returned by a host blocking job.
- Loop
- The platform driver selected for the compilation target; owned by one agent.
- Result
- A fallible turnloop operation preserving portable and native error information.