Alternative future adapters that provide cancel safety.

Overview

cancel-safe-futures

Documentation (main) License License

Alternative futures adapters that are more cancel-safe.

What is this crate?

The futures library contains many adapters that make writing asynchronous Rust code more pleasant. However, some of those combinators make it hard to write code that can withstand cancellation in the case of timeouts, select! branches or similar.

For a more detailed explanation, see the documentation for [SinkExt::reserve].

This crate contains alternative adapters that are designed for use in scenarios where cancellation is expected.

Example

Attempt to send an item in a loop with a timeout:

use cancel_safe_futures::prelude::*;
use std::time::Duration;

let mut my_sink = /* ... */;

// This item is stored here and will be set to None once the loop exits successfully.
let mut item = Some("hello".to_owned());
let do_flush = false;

while item.is_some() {
    match tokio::time::timeout(Duration::from_secs(10), my_sink.reserve()).await {
        Ok(Ok(permit)) => {
            let item = item.take().unwrap();
            if !do_flush {
                // permit.feed() feeds the item into the sink without flushing
                // the sink afterwards. This is a synchronous method.
                permit.feed(item)?;
            } else {
                // Alternatively, permit.send() writes the item into the sink
                // synchronously, then returns a future which can be awaited to
                // flush the sink.
                permit.send(item)?.await?;
            }
        }
        Ok(Err(error)) => return Err(error),
        Err(timeout_error) => continue,
    }
}

Optional features

The std and alloc features are defined and enabled by default, but not currently used. No-std users must turn off default features while importing this crate.

License

This project is available under the terms of either the Apache 2.0 license or the MIT license.

Portions derived from futures-rs, and used under the Apache 2.0 and MIT licenses.

You might also like...
Self-Hosted alternative to GitHub Gists

Gists Self-Hosted GitHub Gists Features Upload code snippets Syntax Highlighting Comments Versioning through Git Fork gists Gist privacy: public, unli

⬢ hexil.org: The libre online alternative to Settlers of Catan

Hexer Getting started for developers Backend Install Rust and Cargo, for example using rustup. Navigate to the back directory. Then start the backend:

Alternative StreamMap fork of tokio-stream

streammap-ext This is a fork of StreamMap from tokio-stream crate. The only difference between the implementations is that this version of StreamMap n

Time-manager of delayed tasks. Like crontab, but synchronous asynchronous tasks are possible, and dynamic add/cancel/remove is supported.
Time-manager of delayed tasks. Like crontab, but synchronous asynchronous tasks are possible, and dynamic add/cancel/remove is supported.

delay-timer Time-manager of delayed tasks. Like crontab, but synchronous asynchronous tasks are possible, and dynamic add/cancel/remove is supported.

Adapters to convert between different writable APIs.

I/O adapters This crate provides adapters to compose writeable traits in the standard library. The following conversions are available: fmt::Write -

A flexible web framework that promotes stability, safety, security and speed.

A flexible web framework that promotes stability, safety, security and speed. Features Stability focused. All releases target stable Rust. This will n

Starlight is a JS engine in Rust which focuses on performance rather than ensuring 100% safety of JS runtime.

starlight Starlight is a JS engine in Rust which focuses on performance rather than ensuring 100% safety of JS runtime. Features Bytecode interpreter

A rust web framework with safety and speed in mind.

darpi A web api framework with speed and safety in mind. One of the big goals is to catch all errors at compile time, if possible. The framework uses

rip is a command-line deletion tool focused on safety, ergonomics, and performance

rip (Rm ImProved) rip is a command-line deletion tool focused on safety, ergonomics, and performance. It favors a simple interface, and does not imple

A cross-platform GUI library for Rust focused on simplicity and type-safety
A cross-platform GUI library for Rust focused on simplicity and type-safety

A cross-platform GUI library for Rust, inspired by Elm

Explore from the safety of your shell
Explore from the safety of your shell

turtlescan Explore from the safety of your shell Installation: cargo install turtlescan tui Starts a little tui which connects to your JSON-RPC server

Rust Memory Safety & Undefined Behavior Detection

Rudra is a static analyzer to detect common undefined behaviors in Rust programs. It is capable of analyzing single Rust packages as well as all the packages on crates.io.

 A new blockchain architecture under active development, with a strong focus on scalability, privacy and safety
A new blockchain architecture under active development, with a strong focus on scalability, privacy and safety

Project Slingshot Accelerating trajectory into interstellar space. Slingshot is a new blockchain architecture under active development, with a strong

A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

A linear algebra library with excellent type safety

Static L.A. (Linear Algebra) A fast minimal ultra type safe linear algebra library. While ndarray offers no compile time type checking on dimensionali

Unopinionated low level API bindings focused on soundness, safety, and stronger types over raw FFI.

🔥 firehazard 🔥 Create a fire hazard by locking down your (Microsoft) Windows so nobody can escape (your security sandbox.) Unopinionated low level A

Assignments of Stanford CS110L-2020spr: Safety in Systems Programming

CS110L Spring 2020: Safety in Systems Programming 课程简介 CS110L将带领我们学习 Rust ,这是一门注重 安全、性能、工程 的语言。 Why Rust? 我的浅显理解是:Rust 被设计出来旨在解决目前系统级编程的困难,其特征 “安全、性能、

Nimbus - A virtual, networked filesystem with strong upfront safety guarantees

The Nimbus Filesystem Nimbus is a virtual, networked filesystem that provides upfront safety guarantees to a user, intended for personal use. In parti

Comments
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • Cargo.toml (cargo)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Upgrade the channel field in the rust-toolchain.toml file if present
    • Enable crate updates in the dependency dashboard
    • Apply Oxide's default rust preset
    • Format GitHub action updates
    • Apply Oxide's default github actions preset
    • Enable Renovate Dependency Dashboard creation.
    • Apply Oxide's global renovate preset

    🔡 Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    It looks like your repository dependencies are already up-to-date and no Pull Requests will be necessary right away.


    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Update Rust crate tokio to 1.29.1

    Update Rust crate tokio to 1.29.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | tokio (source) | dev-dependencies | minor | 1.28.2 -> 1.29.1 |


    Release Notes

    tokio-rs/tokio (tokio)

    v1.29.1: Tokio v1.29.1

    Compare Source

    Fixed
    • rt: fix nesting two block_in_place with a block_on between (#​5837)

    v1.29.0: Tokio v1.29.0

    Compare Source

    Technically a breaking change, the Send implementation is removed from runtime::EnterGuard. This change fixes a bug and should not impact most users.

    Breaking
    • rt: EnterGuard should not be Send (#​5766)
    Fixed
    • fs: reduce blocking ops in fs::read_dir (#​5653)
    • rt: fix possible starvation (#​5686, #​5712)
    • rt: fix stacked borrows issue in JoinSet (#​5693)
    • rt: panic if EnterGuard dropped incorrect order (#​5772)
    • time: do not overflow to signal value (#​5710)
    • fs: wait for in-flight ops before cloning File (#​5803)
    Changed
    • rt: reduce time to poll tasks scheduled from outside the runtime (#​5705, #​5720)
    Added
    • net: add uds doc alias for unix sockets (#​5659)
    • rt: add metric for number of tasks (#​5628)
    • sync: implement more traits for channel errors (#​5666)
    • net: add nodelay methods on TcpSocket (#​5672)
    • sync: add broadcast::Receiver::blocking_recv (#​5690)
    • process: add raw_arg method to Command (#​5704)
    • io: support PRIORITY epoll events (#​5566)
    • task: add JoinSet::poll_join_next (#​5721)
    • net: add support for Redox OS (#​5790)
    Unstable

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Open

    These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

    Detected dependencies

    cargo
    Cargo.toml
    • futures-core 0.3.28
    • futures-sink 0.3.28
    • futures-util 0.3.28
    • tokio 1.28.2
    github-actions
    .github/workflows/ci.yml
    • actions/checkout v3
    • Swatinem/rust-cache v2
    • actions/checkout v3
    • Swatinem/rust-cache v2
    .github/workflows/docs.yml
    • actions/checkout v3
    • Swatinem/rust-cache v2

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Owner
Oxide Computer Company
Servers as they should be.
Oxide Computer Company
A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

null 4 Nov 30, 2022
🌌⭐ Git tooling of the future.

❯ Glitter Git tooling of the future. ❯ ?? Features Config files Fast Easy to use Friendly errors ❯ ?? Documentation For proper docs, see here ❯ ✋ What

Milo 229 Dec 22, 2022
async-alloc-counter measures max allocations in a future invocation

async-alloc-counter measures max allocations in a future invocation see examples/ for usage This allocator can be used as follows: use async_alloc_cou

Geoffroy Couprie 2 Dec 3, 2021
Lupus is a utility to administer backups with future integration with rsync

Lupus is a utility to administer backups with future integration with rsync. Many other features are either included or planned such as chat bridges using rcon and or parsing the pipe output from programs/games.

null 3 Sep 19, 2022
You can name anonymous Future from async fn without dyn or Box!

rename-future You can name anonymous Future from async fn without dyn or Box! PLEASE READ THIS THIS PROJECT NOT YET WELL TESTED! DON'T USE THIS IN PRO

Jun Ryung Ju 54 Sep 17, 2022
An iterator adapter to peek at future elements without advancing the cursor of the underlying iterator.

multipeek An iterator adapter to peek at future elements without advancing the cursor of the underlying iterator. Check out the documentation for more

Luca Palmieri 20 Jul 16, 2022
A future version of Pokétwo

poketwo-next Pokétwo brings the Pokémon experience to Discord. Catch randomly-spawning pokémon in your servers, trade them to expand your collection,

Pokétwo 13 Aug 20, 2022
Rust Stream::buffer_unordered where each future can have a different weight.

buffer-unordered-weighted buffer_unordered_weighted is a variant of buffer_unordered, where each future can be assigned a different weight. This crate

null 15 Dec 28, 2022
Utilities and tools based around Amazon S3 to provide convenience APIs in a CLI

s3-utils Utilities and tools based around Amazon S3 to provide convenience APIs in a CLI. This tool contains a small set of command line utilities for

Isaac Whitfield 47 Dec 15, 2022
This contract is to provide vesting account feature for the both cw20 and native tokens, which is controlled by a master address

Token Vesting This contract is to provide vesting account feature for the both cw20 and native tokens, which is controlled by a master address. Instan

yys 7 Oct 7, 2022