{"id":20696950,"url":"https://github.com/smol-rs/async-compat","last_synced_at":"2025-04-14T00:55:13.784Z","repository":{"id":43661457,"uuid":"291543090","full_name":"smol-rs/async-compat","owner":"smol-rs","description":"Compatibility adapter between tokio and futures","archived":false,"fork":false,"pushed_at":"2025-03-09T03:33:51.000Z","size":41,"stargazers_count":167,"open_issues_count":6,"forks_count":15,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-06T22:02:49.512Z","etag":null,"topics":["async","rust"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/smol-rs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-30T20:03:53.000Z","updated_at":"2025-04-02T09:04:50.000Z","dependencies_parsed_at":"2024-05-31T02:31:10.625Z","dependency_job_id":"5db6af26-948f-4ab2-8532-ecb498c474a4","html_url":"https://github.com/smol-rs/async-compat","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smol-rs%2Fasync-compat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smol-rs%2Fasync-compat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smol-rs%2Fasync-compat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smol-rs%2Fasync-compat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/smol-rs","download_url":"https://codeload.github.com/smol-rs/async-compat/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248804783,"owners_count":21164131,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["async","rust"],"created_at":"2024-11-17T00:16:06.080Z","updated_at":"2025-04-14T00:55:13.758Z","avatar_url":"https://github.com/smol-rs.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# async-compat\n\n[![Build](https://github.com/smol-rs/async-compat/workflows/Build%20and%20test/badge.svg)](\nhttps://github.com/smol-rs/async-compat/actions)\n[![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](\nhttps://github.com/smol-rs/async-compat)\n[![Cargo](https://img.shields.io/crates/v/async-compat.svg)](\nhttps://crates.io/crates/async-compat)\n[![Documentation](https://docs.rs/async-compat/badge.svg)](\nhttps://docs.rs/async-compat)\n\nCompatibility adapter between tokio and futures.\n\nThere are two kinds of compatibility issues between [tokio] and [futures]:\n\n2. Tokio's types cannot be used outside tokio context, so any attempt to use\n   them will panic.\n    - Solution: If you apply the `Compat` adapter to a future, the future will enter the\n      context of a global single-threaded tokio runtime started by this crate. That does\n      *not* mean the future runs on the tokio runtime - it only means the future sets a\n      thread-local variable pointing to the global tokio runtime so that tokio's types can be\n      used inside it.\n2. Tokio and futures have similar but different I/O traits `AsyncRead`, `AsyncWrite`,\n  `AsyncBufRead`, and `AsyncSeek`.\n    - Solution: When the `Compat` adapter is applied to an I/O type, it will implement traits\n      of the opposite kind. That's how you can use tokio-based types wherever futures-based\n      types are expected, and the other way around.\n\n## Examples\n\nThis program reads lines from stdin and echoes them into stdout, except it's not going to work:\n\n```rust\nfn main() -\u003e std::io::Result\u003c()\u003e {\n    futures::executor::block_on(async {\n        let stdin = tokio::io::stdin();\n        let mut stdout = tokio::io::stdout();\n\n        // The following line will not work for two reasons:\n        // 1. Runtime error because stdin and stdout are used outside tokio context.\n        // 2. Compilation error due to mismatched `AsyncRead` and `AsyncWrite` traits.\n        futures::io::copy(stdin, \u0026mut stdout).await?;\n        Ok(())\n    })\n}\n```\n\nTo get around the compatibility issues, apply the `Compat` adapter to `stdin`, `stdout`, and\n[`futures::io::copy()`]:\n\n```rust\nuse async_compat::CompatExt;\n\nfn main() -\u003e std::io::Result\u003c()\u003e {\n    futures::executor::block_on(async {\n        let stdin = tokio::io::stdin();\n        let mut stdout = tokio::io::stdout();\n\n        futures::io::copy(stdin.compat(), \u0026mut stdout.compat_mut()).compat().await?;\n        Ok(())\n    })\n}\n```\n\nIt is also possible to apply `Compat` to the outer future passed to\n[`futures::executor::block_on()`] rather than [`futures::io::copy()`] itself.\nWhen applied to the outer future, individual inner futures don't need the adapter because\nthey're all now inside tokio context:\n\n```rust\nuse async_compat::{Compat, CompatExt};\n\nfn main() -\u003e std::io::Result\u003c()\u003e {\n    futures::executor::block_on(Compat::new(async {\n        let stdin = tokio::io::stdin();\n        let mut stdout = tokio::io::stdout();\n\n        futures::io::copy(stdin.compat(), \u0026mut stdout.compat_mut()).await?;\n        Ok(())\n    }))\n}\n```\n\nThe compatibility adapter converts between tokio-based and futures-based I/O types in any\ndirection. Here's how we can write the same program by using futures-based I/O types inside\ntokio:\n\n```rust\nuse async_compat::CompatExt;\nuse blocking::Unblock;\n\n#[tokio::main]\nasync fn main() -\u003e std::io::Result\u003c()\u003e {\n    let mut stdin = Unblock::new(std::io::stdin());\n    let mut stdout = Unblock::new(std::io::stdout());\n\n    tokio::io::copy(\u0026mut stdin.compat_mut(), \u0026mut stdout.compat_mut()).await?;\n    Ok(())\n}\n```\n\nFinally, we can use any tokio-based crate from any other async runtime.\nHere are [reqwest] and [warp] as an example:\n\n```rust\nuse async_compat::{Compat, CompatExt};\nuse warp::Filter;\n\nfn main() {\n    futures::executor::block_on(Compat::new(async {\n        // Make an HTTP GET request.\n        let response = reqwest::get(\"https://www.rust-lang.org\").await.unwrap();\n        println!(\"{}\", response.text().await.unwrap());\n\n        // Start an HTTP server.\n        let routes = warp::any().map(|| \"Hello from warp!\");\n        warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;\n    }))\n}\n```\n\n[blocking]: https://docs.rs/blocking\n[futures]: https://docs.rs/futures\n[reqwest]: https://docs.rs/reqwest\n[tokio]: https://docs.rs/tokio\n[warp]: https://docs.rs/warp\n[`futures::io::copy()`]: https://docs.rs/futures/0.3/futures/io/fn.copy.html\n[`futures::executor::block_on()`]: https://docs.rs/futures/0.3/futures/executor/fn.block_on.html\n\n## License\n\nLicensed under either of\n\n * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n#### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\ndual licensed as above, without any additional terms or conditions.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsmol-rs%2Fasync-compat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsmol-rs%2Fasync-compat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsmol-rs%2Fasync-compat/lists"}