pax_global_header00006660000000000000000000000064143414064740014521gustar00rootroot0000000000000052 comment=29a075db591aa0117f8e36dd76314cd60492d30d smol-1.3.0/000077500000000000000000000000001434140647400124745ustar00rootroot00000000000000smol-1.3.0/.github/000077500000000000000000000000001434140647400140345ustar00rootroot00000000000000smol-1.3.0/.github/workflows/000077500000000000000000000000001434140647400160715ustar00rootroot00000000000000smol-1.3.0/.github/workflows/ci.yml000066400000000000000000000034501434140647400172110ustar00rootroot00000000000000name: CI on: pull_request: push: branches: - master schedule: - cron: '0 2 * * *' env: RUSTFLAGS: -D warnings RUST_BACKTRACE: 1 jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] rust: [nightly, beta, stable] steps: - uses: actions/checkout@v3 - name: Install Rust # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }} - run: cargo build --all --all-features --all-targets - name: Run cargo check (without dev-dependencies to catch missing feature flags) if: startsWith(matrix.rust, 'nightly') run: cargo check -Z features=dev_dep - run: cargo test msrv: runs-on: ubuntu-latest strategy: matrix: # When updating this, the reminder to update the minimum supported # Rust version in Cargo.toml. rust: ['1.47'] steps: - uses: actions/checkout@v3 - name: Install Rust run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} - run: cargo build clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Rust run: rustup update stable - run: cargo clippy --all-features --all-targets fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Rust run: rustup update stable - run: cargo fmt --all --check security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} smol-1.3.0/.github/workflows/release.yml000066400000000000000000000006011434140647400202310ustar00rootroot00000000000000name: Release on: push: tags: - v[0-9]+.* jobs: create-release: if: github.repository_owner == 'smol-rs' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: taiki-e/create-gh-release-action@v1 with: changelog: CHANGELOG.md branch: master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} smol-1.3.0/.gitignore000066400000000000000000000000231434140647400144570ustar00rootroot00000000000000target/ Cargo.lock smol-1.3.0/CHANGELOG.md000066400000000000000000000060241434140647400143070ustar00rootroot00000000000000# Version 1.3.0 - Remove the dependency on the `once_cell` crate to restore the MSRV. (#241) # Version 1.2.5 - Bump version for docs.rs to pick up latest dependencies. # Version 1.2.4 - Update dependencies. # Version 1.2.3 - Bump version for docs.rs to pick up latest dependencies. # Version 1.2.2 - Bump version for docs.rs to pick up latest dependencies. # Version 1.2.1 - Temporarily downgrade `async-executor`. # Version 1.2.0 - Update all dependencies. # Version 1.1.0 - Update `async-executor`. # Version 1.0.1 - Update dependencies. # Version 1.0.0 - Stabilize. # Version 0.4.2 - Update dependencies. # Version 0.4.1 - Bring back `SMOL_THREADS`. # Version 0.4.0 - Add `process`, `fs`, `net`, `lock`, `channel` modules. - Update all dependencies - Remove `smol::run()`. # Version 0.3.3 - Add `block_on()`. - Use `SMOL_THREADS` environment variable. # Version 0.3.2 - Reexport `FutureExt`. # Version 0.3.1 - Fix some typos in docs. # Version 0.3.0 - Reexport `futures-lite`, `blocking`, `async-executor`. - Re-introduce `smol::run()`. # Version 0.2.0 - Split `smol` into `async-io`, `blocking`, and `multitask`. - Big breaking change - there is now only one type `Task`. # Version 0.1.18 - Support Rust 1.39.0 # Version 0.1.17 - Support more platforms by changing `AtomicU64` to `AtomicUsize`. - Remove `IoEvent` and simplify reactor notification. # Version 0.1.16 - Add `Async::readable()` and `Async::writable()`. # Version 0.1.15 - Fix wakeups lost inside the executor. - Fix a fairness issue in the executor. # Version 0.1.14 - Clear the flag after every call to `react()`. # Version 0.1.13 - Fix deadlocks caused by lost wakeups. - Refactor the executor. # Version 0.1.12 - Fix a bug in `Async::::recv()`. # Version 0.1.11 - Update `wepoll-binding`. - Reduce dependencies. - Replace `nix` with `libc`. - Set minimum required `tokio` version to 0.2. # Version 0.1.10 - Fix incorrectly reported error kind when connecting fails. # Version 0.1.9 - Switch to oneshot-style notifications on all platforms. - Fix a bug that caused 100% CPU usage on Windows. - Deprecate `Async::with()` and `Async::with_mut()`. - Add `Async::read_with()`, `Async::read_with_mut()`, `Async::write_with()`, and `Async::write_with_mut()`. - Fix a bug where eventfd was not closed. # Version 0.1.8 - Revert the use of `blocking` crate. # Version 0.1.7 - Update `blocking` to `0.4.2`. - Make `Task::blocking()` work without `run()`. # Version 0.1.6 - Fix a deadlock by always re-registering `IoEvent`. # Version 0.1.5 - Use `blocking` crate for blocking I/O. - Fix a re-registration bug when in oneshot mode. - Use eventfd on Linux. - More tests. - Fix timeout rounding error in epoll/wepoll. # Version 0.1.4 - Fix a bug in UDS async connect # Version 0.1.3 - Fix the writability check in async connect - More comments and documentation - Better security advice on certificates # Version 0.1.2 - Improved internal docs, fixed typos, and more comments # Version 0.1.1 - Upgrade dependencies # Version 0.1.0 - Initial release smol-1.3.0/CODE_OF_CONDUCT.md000066400000000000000000000122011434140647400152670ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [stjepang@gmail.com](mailto:stjepang@gmail.com). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. smol-1.3.0/Cargo.toml000066400000000000000000000027441434140647400144330ustar00rootroot00000000000000[package] name = "smol" # When publishing a new version: # - Update CHANGELOG.md # - Create "v1.x.y" git tag version = "1.3.0" authors = ["Stjepan Glavina "] edition = "2018" rust-version = "1.47" description = "A small and fast async runtime" license = "Apache-2.0 OR MIT" repository = "https://github.com/smol-rs/smol" keywords = ["async", "await", "future", "io", "networking"] categories = ["asynchronous", "concurrency", "network-programming"] exclude = ["/.*"] [dependencies] async-channel = "1.4.2" async-executor = "1.5.0" async-fs = "1.3.0" async-io = "1.12.0" async-lock = "2.6.0" async-net = "1.4.3" async-process = "1.6.0" blocking = "1.3.0" futures-lite = "1.11.0" [dev-dependencies] anyhow = "1" async-dup = "1" async-h1 = "2" async-native-tls = "0.4" async-tungstenite = { version = "0.17", features = ["async-native-tls"] } ctrlc = "3" doc-comment = "0.3" futures = "0.3" http = "0.2" http-types = "2" hyper = { version = "0.14", default-features = false, features = ["client", "http1", "server", "stream"] } native-tls = "0.2" scraper = "0.13" signal-hook = "0.3" surf = { version = "2", default-features = false, features = ["h1-client"] } tempfile = "3" tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] } tungstenite = "0.17" url = "2" [target.'cfg(target_os = "linux")'.dev-dependencies] inotify = { version = "0.10", default-features = false } nix = "0.24" timerfd = "1" [target.'cfg(windows)'.dev-dependencies] uds_windows = "1" smol-1.3.0/LICENSE-APACHE000066400000000000000000000251371434140647400144300ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. smol-1.3.0/LICENSE-MIT000066400000000000000000000017771434140647400141440ustar00rootroot00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. smol-1.3.0/README.md000066400000000000000000000103711434140647400137550ustar00rootroot00000000000000# smol [![Build](https://github.com/smol-rs/smol/workflows/Build%20and%20test/badge.svg)]( https://github.com/smol-rs/smol/actions) [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( https://github.com/smol-rs/smol) [![Cargo](https://img.shields.io/crates/v/smol.svg)]( https://crates.io/crates/smol) [![Documentation](https://docs.rs/smol/badge.svg)]( https://docs.rs/smol) [![Chat](https://img.shields.io/discord/701824908866617385.svg?logo=discord)]( https://discord.gg/x6m5Vvt) A small and fast async runtime. This crate simply re-exports other smaller async crates (see the source). To use tokio-based libraries with smol, apply the [`async-compat`] adapter to futures and I/O types. ## Examples Connect to an HTTP website, make a GET request, and pipe the response to the standard output: ```rust,no_run use smol::{io, net, prelude::*, Unblock}; fn main() -> io::Result<()> { smol::block_on(async { let mut stream = net::TcpStream::connect("example.com:80").await?; let req = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"; stream.write_all(req).await?; let mut stdout = Unblock::new(std::io::stdout()); io::copy(stream, &mut stdout).await?; Ok(()) }) } ``` There's a lot more in the [examples] directory. [`async-compat`]: https://docs.rs/async-compat [examples]: https://github.com/smol-rs/smol/tree/master/examples [get-request]: https://github.com/smol-rs/smol/blob/master/examples/get-request.rs ## Subcrates - [async-channel] - Multi-producer multi-consumer channels - [async-executor] - Composable async executors - [async-fs] - Async filesystem primitives - [async-io] - Async adapter for I/O types, also timers - [async-lock] - Async locks (barrier, mutex, reader-writer lock, semaphore) - [async-net] - Async networking primitives (TCP/UDP/Unix) - [async-process] - Async interface for working with processes - [async-task] - Task abstraction for building executors - [blocking] - A thread pool for blocking I/O - [futures-lite] - A lighter fork of [futures] - [polling] - Portable interface to epoll, kqueue, event ports, and wepoll [async-io]: https://github.com/smol-rs/async-io [polling]: https://github.com/smol-rs/polling [nb-connect]: https://github.com/smol-rs/nb-connect [async-executor]: https://github.com/smol-rs/async-executor [async-task]: https://github.com/smol-rs/async-task [blocking]: https://github.com/smol-rs/blocking [futures-lite]: https://github.com/smol-rs/futures-lite [smol]: https://github.com/smol-rs/smol [async-net]: https://github.com/smol-rs/async-net [async-process]: https://github.com/smol-rs/async-process [async-fs]: https://github.com/smol-rs/async-fs [async-channel]: https://github.com/smol-rs/async-channel [concurrent-queue]: https://github.com/smol-rs/concurrent-queue [event-listener]: https://github.com/smol-rs/event-listener [async-lock]: https://github.com/smol-rs/async-lock [fastrand]: https://github.com/smol-rs/fastrand [futures]: https://github.com/rust-lang/futures-rs ## TLS certificate Some code examples are using TLS for authentication. The repository contains a self-signed certificate usable for testing, but it should **not** be used for real-world scenarios. Browsers and tools like curl will show this certificate as insecure. In browsers, accept the security prompt or use `curl -k` on the command line to bypass security warnings. The certificate file was generated using [minica](https://github.com/jsha/minica) and [openssl](https://www.openssl.org/): ```text minica --domains localhost -ip-addresses 127.0.0.1 -ca-cert certificate.pem openssl pkcs12 -export -out identity.pfx -inkey localhost/key.pem -in localhost/cert.pem ``` Another useful tool for making certificates is [mkcert]. [mkcert]: https://github.com/FiloSottile/mkcert ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. smol-1.3.0/examples/000077500000000000000000000000001434140647400143125ustar00rootroot00000000000000smol-1.3.0/examples/async-h1-client.rs000066400000000000000000000036551434140647400175700ustar00rootroot00000000000000//! An HTTP+TLS client based on `async-h1` and `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example async-h1-client //! ``` use std::net::{TcpStream, ToSocketAddrs}; use anyhow::{bail, Context as _, Error, Result}; use http_types::{Method, Request, Response}; use smol::{prelude::*, Async}; use url::Url; /// Sends a request and fetches the response. async fn fetch(req: Request) -> Result { // Figure out the host and the port. let host = req.url().host().context("cannot parse host")?.to_string(); let port = req .url() .port_or_known_default() .context("cannot guess port")?; // Connect to the host. let socket_addr = { let host = host.clone(); smol::unblock(move || (host.as_str(), port).to_socket_addrs()) .await? .next() .context("cannot resolve address")? }; let stream = Async::::connect(socket_addr).await?; // Send the request and wait for the response. let resp = match req.url().scheme() { "http" => async_h1::connect(stream, req).await.map_err(Error::msg)?, "https" => { // In case of HTTPS, establish a secure TLS connection first. let stream = async_native_tls::connect(&host, stream).await?; async_h1::connect(stream, req).await.map_err(Error::msg)? } scheme => bail!("unsupported scheme: {}", scheme), }; Ok(resp) } fn main() -> Result<()> { smol::block_on(async { // Create a request. let addr = "https://www.rust-lang.org"; let req = Request::new(Method::Get, Url::parse(addr)?); // Fetch the response. let mut resp = fetch(req).await?; println!("{:#?}", resp); // Read the message body. let mut body = Vec::new(); resp.read_to_end(&mut body).await?; println!("{}", String::from_utf8_lossy(&body)); Ok(()) }) } smol-1.3.0/examples/async-h1-server.rs000066400000000000000000000063121434140647400176110ustar00rootroot00000000000000//! An HTTP+TLS server based on `async-h1` and `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example async-h1-server //! ``` //! //! Open in the browser any of these addresses: //! //! - http://localhost:8000/ //! - https://localhost:8001/ (accept the security prompt in the browser) //! //! Refer to `README.md` to see how to the TLS certificate was generated. use std::net::TcpListener; use anyhow::Result; use async_native_tls::{Identity, TlsAcceptor}; use http_types::{Request, Response, StatusCode}; use smol::{future, Async}; /// Serves a request and returns a response. async fn serve(req: Request) -> http_types::Result { println!("Serving {}", req.url()); let mut res = Response::new(StatusCode::Ok); res.insert_header("Content-Type", "text/plain"); res.set_body("Hello from async-h1!"); Ok(res) } /// Listens for incoming connections and serves them. async fn listen(listener: Async, tls: Option) -> Result<()> { // Format the full host address. let host = match &tls { None => format!("http://{}", listener.get_ref().local_addr()?), Some(_) => format!("https://{}", listener.get_ref().local_addr()?), }; println!("Listening on {}", host); loop { // Accept the next connection. let (stream, _) = listener.accept().await?; // Spawn a background task serving this connection. let task = match &tls { None => { let stream = async_dup::Arc::new(stream); smol::spawn(async move { if let Err(err) = async_h1::accept(stream, serve).await { println!("Connection error: {:#?}", err); } }) } Some(tls) => { // In case of HTTPS, establish a secure TLS connection first. match tls.accept(stream).await { Ok(stream) => { let stream = async_dup::Arc::new(async_dup::Mutex::new(stream)); smol::spawn(async move { if let Err(err) = async_h1::accept(stream, serve).await { println!("Connection error: {:#?}", err); } }) } Err(err) => { println!("Failed to establish secure TLS connection: {:#?}", err); continue; } } } }; // Detach the task to let it run in the background. task.detach(); } } fn main() -> Result<()> { // Initialize TLS with the local certificate, private key, and password. let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?; let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?); // Start HTTP and HTTPS servers. smol::block_on(async { let http = listen(Async::::bind(([127, 0, 0, 1], 8000))?, None); let https = listen( Async::::bind(([127, 0, 0, 1], 8001))?, Some(tls), ); future::try_zip(http, https).await?; Ok(()) }) } smol-1.3.0/examples/certificate.pem000066400000000000000000000022641434140647400173030ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDSzCCAjOgAwIBAgIIHBgnI8QV+zIwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE AxMVbWluaWNhIHJvb3QgY2EgMWMxODI3MCAXDTIwMDMyNjE3Mjk1M1oYDzIxMjAw MzI2MTcyOTUzWjAgMR4wHAYDVQQDExVtaW5pY2Egcm9vdCBjYSAxYzE4MjcwggEi MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC5CGrfOjgWhDC67fUL5S/GSYC4 8jP+/NLsxY8bbmohQv9TBOl3Pxv3w5uVXHBhpwigaOyRqvF3+U/YoZgT99QkV+5c XjYjdxgmTEl35eZfT7kCr6PjxLuVOIYdMEYVe+7JgkIMZjEMkRq3giBJxIQ86FWi KhCyg+5vMZ0ZYbfiv+yyfS41JebgJP1WbuR/boT3X90EuyJ3U2F58lOZadXdqJ0T iTLXyZzy7XKFP+3/dhB3NO5kfHhuP6sCHc6ORfkbYUE+rxuwKgwtVdYoBEI9mZMo bZKkyUN4xOzupYKFpKXRBc0UiQKsl+RQ6VCrOM4sc4rWoWHLvj9esP4rbhu7AgMB AAGjgYYwgYMwDgYDVR0PAQH/BAQDAgKEMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggr BgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBTEJVhl2F/WAKdO Br26/llSB4kYSDAfBgNVHSMEGDAWgBTEJVhl2F/WAKdOBr26/llSB4kYSDANBgkq hkiG9w0BAQsFAAOCAQEAkvxlm+mhMn/UBV06jxTLNFan2ttQ79ms7T7EkbQWW55f R3ytzumfR52np4u04K0L6xHTE5vLuNiebq5s8IU7GiWcJWNkCxcJejzgAukFgsbb Ffqg8wBS/tbCaw32btk/lFrJ74t8Q13QDQVSRO9S8S4bHtiSluyV65oPKE2hXbiS euISC+9Yf2Eb4xCqIIb2/hCUq6DF9/tkAffapjbrIKQQjrMqvX6734X7g2N7cwvD Lt7U9YI0CuWHu/L+cpo7+YrBMRgM8tECip61XMQ6oBgJt3ZNMnrYiMkwCeWstKFD tDQJZyAJHE4wbInYqi78rQRMo1eoAfdFcgdS0fyDrA== -----END CERTIFICATE----- smol-1.3.0/examples/chat-client.rs000066400000000000000000000024671434140647400170640ustar00rootroot00000000000000//! A TCP chat client. //! //! First start a server: //! //! ``` //! cargo run --example chat-server //! ``` //! //! Then start clients: //! //! ``` //! cargo run --example chat-client //! ``` use std::net::TcpStream; use smol::{future, io, Async, Unblock}; fn main() -> io::Result<()> { smol::block_on(async { // Connect to the server and create async stdin and stdout. let stream = Async::::connect(([127, 0, 0, 1], 6000)).await?; let stdin = Unblock::new(std::io::stdin()); let mut stdout = Unblock::new(std::io::stdout()); // Intro messages. println!("Connected to {}", stream.get_ref().peer_addr()?); println!("My nickname: {}", stream.get_ref().local_addr()?); println!("Type a message and hit enter!\n"); let reader = &stream; let mut writer = &stream; // Wait until the standard input is closed or the connection is closed. future::race( async { let res = io::copy(stdin, &mut writer).await; println!("Quit!"); res }, async { let res = io::copy(reader, &mut stdout).await; println!("Server disconnected!"); res }, ) .await?; Ok(()) }) } smol-1.3.0/examples/chat-server.rs000066400000000000000000000065611434140647400171130ustar00rootroot00000000000000//! A TCP chat server. //! //! First start a server: //! //! ``` //! cargo run --example chat-server //! ``` //! //! Then start clients: //! //! ``` //! cargo run --example chat-client //! ``` use std::collections::HashMap; use std::net::{SocketAddr, TcpListener, TcpStream}; use async_channel::{bounded, Receiver, Sender}; use async_dup::Arc; use smol::{io, prelude::*, Async}; /// An event on the chat server. enum Event { /// A client has joined. Join(SocketAddr, Arc>), /// A client has left. Leave(SocketAddr), /// A client sent a message. Message(SocketAddr, String), } /// Dispatches events to clients. async fn dispatch(receiver: Receiver) -> io::Result<()> { // Currently active clients. let mut map = HashMap::>>::new(); // Receive incoming events. while let Ok(event) = receiver.recv().await { // Process the event and format a message to send to clients. let output = match event { Event::Join(addr, stream) => { map.insert(addr, stream); format!("{} has joined\n", addr) } Event::Leave(addr) => { map.remove(&addr); format!("{} has left\n", addr) } Event::Message(addr, msg) => format!("{} says: {}\n", addr, msg), }; // Display the event in the server process. print!("{}", output); // Send the event to all active clients. for stream in map.values_mut() { // Ignore errors because the client might disconnect at any point. stream.write_all(output.as_bytes()).await.ok(); } } Ok(()) } /// Reads messages from the client and forwards them to the dispatcher task. async fn read_messages(sender: Sender, client: Arc>) -> io::Result<()> { let addr = client.get_ref().peer_addr()?; let mut lines = io::BufReader::new(client).lines(); while let Some(line) = lines.next().await { let line = line?; sender.send(Event::Message(addr, line)).await.ok(); } Ok(()) } fn main() -> io::Result<()> { smol::block_on(async { // Create a listener for incoming client connections. let listener = Async::::bind(([127, 0, 0, 1], 6000))?; // Intro messages. println!("Listening on {}", listener.get_ref().local_addr()?); println!("Start a chat client now!\n"); // Spawn a background task that dispatches events to clients. let (sender, receiver) = bounded(100); smol::spawn(dispatch(receiver)).detach(); loop { // Accept the next connection. let (stream, addr) = listener.accept().await?; let client = Arc::new(stream); let sender = sender.clone(); // Spawn a background task reading messages from the client. smol::spawn(async move { // Client starts with a `Join` event. sender.send(Event::Join(addr, client.clone())).await.ok(); // Read messages from the client and ignore I/O errors when the client quits. read_messages(sender.clone(), client).await.ok(); // Client ends with a `Leave` event. sender.send(Event::Leave(addr)).await.ok(); }) .detach(); } }) } smol-1.3.0/examples/ctrl-c.rs000066400000000000000000000010701434140647400160420ustar00rootroot00000000000000//! Uses the `ctrlc` crate to catch the Ctrl-C signal. //! //! Run with: //! //! ``` //! cargo run --example ctrl-c //! ``` fn main() { // Set a handler that sends a message through a channel. let (s, ctrl_c) = async_channel::bounded(100); let handle = move || { s.try_send(()).ok(); }; ctrlc::set_handler(handle).unwrap(); smol::block_on(async { println!("Waiting for Ctrl-C..."); // Receive a message that indicates the Ctrl-C signal occurred. ctrl_c.recv().await.ok(); println!("Done!"); }) } smol-1.3.0/examples/get-request.rs000066400000000000000000000016261434140647400171320ustar00rootroot00000000000000//! Connect to an HTTP website, make a GET request, and pipe the response to the standard output. //! //! Run with: //! //! ``` //! cargo run --example get-request //! ``` use smol::{io, prelude::*, Async, Unblock}; use std::net::{TcpStream, ToSocketAddrs}; fn main() -> io::Result<()> { smol::block_on(async { // Connect to http://example.com let mut addrs = smol::unblock(move || ("example.com", 80).to_socket_addrs()).await?; let addr = addrs.next().unwrap(); let mut stream = Async::::connect(addr).await?; // Send an HTTP GET request. let req = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"; stream.write_all(req).await?; // Read the response and pipe it to the standard output. let mut stdout = Unblock::new(std::io::stdout()); io::copy(&stream, &mut stdout).await?; Ok(()) }) } smol-1.3.0/examples/hyper-client.rs000066400000000000000000000127421434140647400172710ustar00rootroot00000000000000//! An HTTP+TLS client based on `hyper` and `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example hyper-client //! ``` use std::net::Shutdown; use std::net::{TcpStream, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::{bail, Context as _, Error, Result}; use async_native_tls::TlsStream; use http::Uri; use hyper::{Body, Client, Request, Response}; use smol::{io, prelude::*, Async}; /// Sends a request and fetches the response. async fn fetch(req: Request) -> Result> { Ok(Client::builder() .executor(SmolExecutor) .build::<_, Body>(SmolConnector) .request(req) .await?) } fn main() -> Result<()> { smol::block_on(async { // Create a request. let req = Request::get("https://www.rust-lang.org").body(Body::empty())?; // Fetch the response. let resp = fetch(req).await?; println!("{:#?}", resp); // Read the message body. let body = resp .into_body() .try_fold(Vec::new(), |mut body, chunk| { body.extend_from_slice(&chunk); Ok(body) }) .await?; println!("{}", String::from_utf8_lossy(&body)); Ok(()) }) } /// Spawns futures. #[derive(Clone)] struct SmolExecutor; impl hyper::rt::Executor for SmolExecutor { fn execute(&self, fut: F) { smol::spawn(async { drop(fut.await) }).detach(); } } /// Connects to URLs. #[derive(Clone)] struct SmolConnector; impl hyper::service::Service for SmolConnector { type Response = SmolStream; type Error = Error; type Future = Pin> + Send>>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, uri: Uri) -> Self::Future { Box::pin(async move { let host = uri.host().context("cannot parse host")?; match uri.scheme_str() { Some("http") => { let socket_addr = { let host = host.to_string(); let port = uri.port_u16().unwrap_or(80); smol::unblock(move || (host.as_str(), port).to_socket_addrs()) .await? .next() .context("cannot resolve address")? }; let stream = Async::::connect(socket_addr).await?; Ok(SmolStream::Plain(stream)) } Some("https") => { // In case of HTTPS, establish a secure TLS connection first. let socket_addr = { let host = host.to_string(); let port = uri.port_u16().unwrap_or(443); smol::unblock(move || (host.as_str(), port).to_socket_addrs()) .await? .next() .context("cannot resolve address")? }; let stream = Async::::connect(socket_addr).await?; let stream = async_native_tls::connect(host, stream).await?; Ok(SmolStream::Tls(stream)) } scheme => bail!("unsupported scheme: {:?}", scheme), } }) } } /// A TCP or TCP+TLS connection. enum SmolStream { /// A plain TCP connection. Plain(Async), /// A TCP connection secured by TLS. Tls(TlsStream>), } impl hyper::client::connect::Connection for SmolStream { fn connected(&self) -> hyper::client::connect::Connected { hyper::client::connect::Connected::new() } } impl tokio::io::AsyncRead for SmolStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll> { match &mut *self { SmolStream::Plain(s) => { Pin::new(s) .poll_read(cx, buf.initialize_unfilled()) .map_ok(|size| { buf.advance(size); }) } SmolStream::Tls(s) => { Pin::new(s) .poll_read(cx, buf.initialize_unfilled()) .map_ok(|size| { buf.advance(size); }) } } } } impl tokio::io::AsyncWrite for SmolStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { match &mut *self { SmolStream::Plain(s) => Pin::new(s).poll_write(cx, buf), SmolStream::Tls(s) => Pin::new(s).poll_write(cx, buf), } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { SmolStream::Plain(s) => Pin::new(s).poll_flush(cx), SmolStream::Tls(s) => Pin::new(s).poll_flush(cx), } } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { SmolStream::Plain(s) => { s.get_ref().shutdown(Shutdown::Write)?; Poll::Ready(Ok(())) } SmolStream::Tls(s) => Pin::new(s).poll_close(cx), } } } smol-1.3.0/examples/hyper-server.rs000066400000000000000000000151771434140647400173260ustar00rootroot00000000000000//! An HTTP+TLS server based on `hyper` and `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example hyper-server //! ``` //! //! Open in the browser any of these addresses: //! //! - http://localhost:8000/ //! - https://localhost:8001/ (accept the security prompt in the browser) //! //! Refer to `README.md` to see how to the TLS certificate was generated. use std::net::{Shutdown, TcpListener, TcpStream}; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::{Error, Result}; use async_native_tls::{Identity, TlsAcceptor, TlsStream}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use smol::{future, io, prelude::*, Async}; /// Serves a request and returns a response. async fn serve(req: Request, host: String) -> Result> { println!("Serving {}{}", host, req.uri()); Ok(Response::new(Body::from("Hello from hyper!"))) } /// Listens for incoming connections and serves them. async fn listen(listener: Async, tls: Option) -> Result<()> { // Format the full host address. let host = &match tls { None => format!("http://{}", listener.get_ref().local_addr()?), Some(_) => format!("https://{}", listener.get_ref().local_addr()?), }; println!("Listening on {}", host); // Start a hyper server. Server::builder(SmolListener::new(&listener, tls)) .executor(SmolExecutor) .serve(make_service_fn(move |_| { let host = host.clone(); async { Ok::<_, Error>(service_fn(move |req| serve(req, host.clone()))) } })) .await?; Ok(()) } fn main() -> Result<()> { // Initialize TLS with the local certificate, private key, and password. let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?; let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?); // Start HTTP and HTTPS servers. smol::block_on(async { let http = listen(Async::::bind(([127, 0, 0, 1], 8000))?, None); let https = listen( Async::::bind(([127, 0, 0, 1], 8001))?, Some(tls), ); future::try_zip(http, https).await?; Ok(()) }) } /// Spawns futures. #[derive(Clone)] struct SmolExecutor; impl hyper::rt::Executor for SmolExecutor { fn execute(&self, fut: F) { smol::spawn(async { drop(fut.await) }).detach(); } } /// Listens for incoming connections. struct SmolListener<'a> { tls: Option, incoming: Pin>> + Send + 'a>>, } impl<'a> SmolListener<'a> { fn new(listener: &'a Async, tls: Option) -> Self { Self { incoming: Box::pin(listener.incoming()), tls, } } } impl hyper::server::accept::Accept for SmolListener<'_> { type Conn = SmolStream; type Error = Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll>> { let stream = smol::ready!(self.incoming.as_mut().poll_next(cx)).unwrap()?; let stream = match &self.tls { None => SmolStream::Plain(stream), Some(tls) => { // In case of HTTPS, start establishing a secure TLS connection. let tls = tls.clone(); SmolStream::Handshake(Box::pin(async move { tls.accept(stream).await.map_err(|err| { println!("Failed to establish secure TLS connection: {:#?}", err); io::Error::new(io::ErrorKind::Other, Box::new(err)) }) })) } }; Poll::Ready(Some(Ok(stream))) } } /// A TCP or TCP+TLS connection. enum SmolStream { /// A plain TCP connection. Plain(Async), /// A TCP connection secured by TLS. Tls(TlsStream>), /// A TCP connection that is in process of getting secured by TLS. #[allow(clippy::type_complexity)] Handshake(Pin>>> + Send>>), } impl hyper::client::connect::Connection for SmolStream { fn connected(&self) -> hyper::client::connect::Connected { hyper::client::connect::Connected::new() } } impl tokio::io::AsyncRead for SmolStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll> { loop { match &mut *self { SmolStream::Plain(s) => { return Pin::new(s) .poll_read(cx, buf.initialize_unfilled()) .map_ok(|size| { buf.advance(size); }); } SmolStream::Tls(s) => { return Pin::new(s) .poll_read(cx, buf.initialize_unfilled()) .map_ok(|size| { buf.advance(size); }); } SmolStream::Handshake(f) => { let s = smol::ready!(f.as_mut().poll(cx))?; *self = SmolStream::Tls(s); } } } } } impl tokio::io::AsyncWrite for SmolStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { loop { match &mut *self { SmolStream::Plain(s) => return Pin::new(s).poll_write(cx, buf), SmolStream::Tls(s) => return Pin::new(s).poll_write(cx, buf), SmolStream::Handshake(f) => { let s = smol::ready!(f.as_mut().poll(cx))?; *self = SmolStream::Tls(s); } } } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { SmolStream::Plain(s) => Pin::new(s).poll_flush(cx), SmolStream::Tls(s) => Pin::new(s).poll_flush(cx), SmolStream::Handshake(_) => Poll::Ready(Ok(())), } } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { SmolStream::Plain(s) => { s.get_ref().shutdown(Shutdown::Write)?; Poll::Ready(Ok(())) } SmolStream::Tls(s) => Pin::new(s).poll_close(cx), SmolStream::Handshake(_) => Poll::Ready(Ok(())), } } } smol-1.3.0/examples/identity.pfx000066400000000000000000000045651434140647400166740ustar00rootroot000000000000000 q0 7 *H  ( $0 0 *H 00 *H 0 *H  0Jpֽ~{y c:0K~ێ{I*~ M8ӳTZT)͵M}bBY+"CE?慚"-`$߳?swLBn1Ih㤵4X5\S0h| ~wW\ giU$[@Tw dPqq7KwQGBb*aRR&iU}ƅ0 ט_ե,]x2_">᯾ >3 QE}v̟a (ࣆ wH35) (5jqj1!5}n %a=UqS<A$?SӲ75j vc k rZW⯨nfkpcip@b8&ܧy^KIz(?r@uSI1:}(: N-.8IN+'SSk*`o*Z?fay\B.`#^wwRS0;+[kw>#M15WRe9Rډ-SڝwQe FKzΙ2up>uĆ秅t4T`cC`E.ϾfJjfp6Ȯ͚W;G 0A *H 2.0*0& *H  00 *H  03)YBj 4i!sFŽLDoA€r^F&V*x}npU 5R8ˠv.I)c8xQs(0J س\)NQ&vSc7bLKLq b>Q;hX7@Qm %Ln,ls0}fцܚAvԀpXcFXd$+T FԫL [ Kv>MѬɏ'7́`N<0rOp6B>劳r2͗Wy {9>0,5 FI%`G_I+՗1Z*XWШWWrd3CG5N6ZD2`,)N!pdr)0M(a<(@ĵy`cͣQaITӴ/J˩OzuHwg[5iGY>FM@ߴ-sPcajxMfΗ_e|d3nXrNL bv!(ε3P 62ܳY̸mzh1ؾ[mٞ-ۦ| |['+> #"V]!1d:=Zlt٘R'V(uWg&"/MsS-:)E!@@U66]j)^"CŁΠܩԀ8EWl std::io::Result<()> { use std::ffi::OsString; use inotify::{EventMask, Inotify, WatchMask}; use smol::{io, Async}; type Event = (OsString, EventMask); /// Reads some events without blocking. /// /// If there are no events, an [`io::ErrorKind::WouldBlock`] error is returned. fn read_op(inotify: &mut Inotify) -> io::Result> { let mut buffer = [0; 1024]; let events = inotify .read_events(&mut buffer)? .filter_map(|ev| ev.name.map(|name| (name.to_owned(), ev.mask))) .collect::>(); if events.is_empty() { Err(io::ErrorKind::WouldBlock.into()) } else { Ok(events) } } smol::block_on(async { // Watch events in the current directory. let mut inotify = Async::new(Inotify::init()?)?; inotify.get_mut().add_watch(".", WatchMask::ALL_EVENTS)?; println!("Watching for filesystem events in the current directory..."); println!("Try opening a file to trigger some events."); println!(); // Wait for events in a loop and print them on the screen. loop { for event in inotify.read_with_mut(read_op).await? { println!("{:?}", event); } } }) } #[cfg(not(target_os = "linux"))] fn main() { println!("This example works only on Linux!"); } smol-1.3.0/examples/linux-timerfd.rs000066400000000000000000000022711434140647400174510ustar00rootroot00000000000000//! Uses the `timerfd` crate to sleep using an OS timer. //! //! Run with: //! //! ``` //! cargo run --example linux-timerfd //! ``` #[cfg(target_os = "linux")] fn main() -> std::io::Result<()> { use std::os::unix::io::AsRawFd; use std::time::{Duration, Instant}; use smol::{io, Async}; use timerfd::{SetTimeFlags, TimerFd, TimerState}; /// Sleeps using an OS timer. async fn sleep(dur: Duration) -> io::Result<()> { // Create an OS timer. let mut timer = TimerFd::new()?; timer.set_state(TimerState::Oneshot(dur), SetTimeFlags::Default); // When the OS timer fires, a 64-bit integer can be read from it. Async::new(timer)? .read_with(|t| nix::unistd::read(t.as_raw_fd(), &mut [0u8; 8]).map_err(io::Error::from)) .await?; Ok(()) } smol::block_on(async { let start = Instant::now(); println!("Sleeping..."); // Sleep for a second using an OS timer. sleep(Duration::from_secs(1)).await?; println!("Woke up after {:?}", start.elapsed()); Ok(()) }) } #[cfg(not(target_os = "linux"))] fn main() { println!("This example works only on Linux!"); } smol-1.3.0/examples/simple-client.rs000066400000000000000000000037631434140647400174360ustar00rootroot00000000000000//! A simple HTTP+TLS client based on `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example simple-client //! ``` use std::net::{TcpStream, ToSocketAddrs}; use anyhow::{bail, Context as _, Result}; use smol::{prelude::*, Async}; use url::Url; /// Sends a GET request and fetches the response. async fn fetch(addr: &str) -> Result> { // Parse the URL. let url = Url::parse(addr)?; let host = url.host().context("cannot parse host")?.to_string(); let port = url.port_or_known_default().context("cannot guess port")?; let path = url.path().to_string(); let query = match url.query() { Some(q) => format!("?{}", q), None => String::new(), }; // Construct a request. let req = format!( "GET {}{} HTTP/1.1\r\nHost: {}\r\nAccept: */*\r\nConnection: close\r\n\r\n", path, query, host, ); // Connect to the host. let socket_addr = { let host = host.clone(); smol::unblock(move || (host.as_str(), port).to_socket_addrs()) .await? .next() .context("cannot resolve address")? }; let mut stream = Async::::connect(socket_addr).await?; // Send the request and wait for the response. let mut resp = Vec::new(); match url.scheme() { "http" => { stream.write_all(req.as_bytes()).await?; stream.read_to_end(&mut resp).await?; } "https" => { // In case of HTTPS, establish a secure TLS connection first. let mut stream = async_native_tls::connect(&host, stream).await?; stream.write_all(req.as_bytes()).await?; stream.read_to_end(&mut resp).await?; } scheme => bail!("unsupported scheme: {}", scheme), } Ok(resp) } fn main() -> Result<()> { smol::block_on(async { let addr = "https://www.rust-lang.org"; let resp = fetch(addr).await?; println!("{}", String::from_utf8_lossy(&resp)); Ok(()) }) } smol-1.3.0/examples/simple-server.rs000066400000000000000000000055431434140647400174640ustar00rootroot00000000000000//! A simple HTTP+TLS server based on `async-native-tls`. //! //! Run with: //! //! ``` //! cargo run --example simple-server //! ``` //! //! Open in the browser any of these addresses: //! //! - http://localhost:8000/ //! - https://localhost:8001/ (accept the security prompt in the browser) //! //! Refer to `README.md` to see how to the TLS certificate was generated. use std::net::{TcpListener, TcpStream}; use anyhow::Result; use async_native_tls::{Identity, TlsAcceptor}; use smol::{future, prelude::*, Async}; const RESPONSE: &[u8] = br#" HTTP/1.1 200 OK Content-Type: text/html Content-Length: 47 Hello! "#; /// Reads a request from the client and sends it a response. async fn serve(mut stream: Async, tls: Option) -> Result<()> { match tls { None => { println!("Serving http://{}", stream.get_ref().local_addr()?); stream.write_all(RESPONSE).await?; } Some(tls) => { println!("Serving https://{}", stream.get_ref().local_addr()?); // In case of HTTPS, establish a secure TLS connection first. match tls.accept(stream).await { Ok(mut stream) => { stream.write_all(RESPONSE).await?; stream.flush().await?; stream.close().await?; } Err(err) => println!("Failed to establish secure TLS connection: {:#?}", err), } } } Ok(()) } /// Listens for incoming connections and serves them. async fn listen(listener: Async, tls: Option) -> Result<()> { // Display the full host address. match &tls { None => println!("Listening on http://{}", listener.get_ref().local_addr()?), Some(_) => println!("Listening on https://{}", listener.get_ref().local_addr()?), } loop { // Accept the next connection. let (stream, _) = listener.accept().await?; let tls = tls.clone(); // Spawn a background task serving this connection. smol::spawn(async move { if let Err(err) = serve(stream, tls).await { println!("Connection error: {:#?}", err); } }) .detach(); } } fn main() -> Result<()> { // Initialize TLS with the local certificate, private key, and password. let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?; let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?); // Start HTTP and HTTPS servers. smol::block_on(async { let http = listen(Async::::bind(([127, 0, 0, 1], 8000))?, None); let https = listen( Async::::bind(([127, 0, 0, 1], 8001))?, Some(tls), ); future::try_zip(http, https).await?; Ok(()) }) } smol-1.3.0/examples/tcp-client.rs000066400000000000000000000017111434140647400167220ustar00rootroot00000000000000//! A TCP client. //! //! First start a server: //! //! ``` //! cargo run --example tcp-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example tcp-client //! ``` use std::net::TcpStream; use smol::{future, io, Async, Unblock}; fn main() -> io::Result<()> { smol::block_on(async { // Create async stdin and stdout handles. let stdin = Unblock::new(std::io::stdin()); let mut stdout = Unblock::new(std::io::stdout()); // Connect to the server. let stream = Async::::connect(([127, 0, 0, 1], 7000)).await?; println!("Connected to {}", stream.get_ref().peer_addr()?); println!("Type a message and hit enter!\n"); // Pipe messages from stdin to the server and pipe messages from the server to stdout. future::try_zip( io::copy(stdin, &mut &stream), io::copy(&stream, &mut stdout), ) .await?; Ok(()) }) } smol-1.3.0/examples/tcp-server.rs000066400000000000000000000017701434140647400167570ustar00rootroot00000000000000//! A TCP server. //! //! First start a server: //! //! ``` //! cargo run --example tcp-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example tcp-client //! ``` use std::net::{TcpListener, TcpStream}; use smol::{io, Async}; /// Echoes messages from the client back to it. async fn echo(stream: Async) -> io::Result<()> { io::copy(&stream, &mut &stream).await?; Ok(()) } fn main() -> io::Result<()> { smol::block_on(async { // Create a listener. let listener = Async::::bind(([127, 0, 0, 1], 7000))?; println!("Listening on {}", listener.get_ref().local_addr()?); println!("Now start a TCP client."); // Accept clients in a loop. loop { let (stream, peer_addr) = listener.accept().await?; println!("Accepted client: {}", peer_addr); // Spawn a task that echoes messages from the client back to it. smol::spawn(echo(stream)).detach(); } }) } smol-1.3.0/examples/tls-client.rs000066400000000000000000000026511434140647400167420ustar00rootroot00000000000000//! A TCP client secured by TLS based on `async-native-tls`. //! //! First start a server: //! //! ``` //! cargo run --example tls-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example tls-client //! ``` use std::net::TcpStream; use anyhow::Result; use async_native_tls::{Certificate, TlsConnector}; use smol::{future, io, Async, Unblock}; fn main() -> Result<()> { // Initialize TLS with the local certificate. let mut builder = native_tls::TlsConnector::builder(); builder.add_root_certificate(Certificate::from_pem(include_bytes!("certificate.pem"))?); let tls = TlsConnector::from(builder); smol::block_on(async { // Create async stdin and stdout handles. let stdin = Unblock::new(std::io::stdin()); let mut stdout = Unblock::new(std::io::stdout()); // Connect to the server. let stream = Async::::connect(([127, 0, 0, 1], 7001)).await?; let stream = tls.connect("127.0.0.1", stream).await?; println!("Connected to {}", stream.get_ref().get_ref().peer_addr()?); println!("Type a message and hit enter!\n"); // Pipe messages from stdin to the server and pipe messages from the server to stdout. let stream = async_dup::Mutex::new(stream); future::try_zip( io::copy(stdin, &mut &stream), io::copy(&stream, &mut stdout), ) .await?; Ok(()) }) } smol-1.3.0/examples/tls-server.rs000066400000000000000000000030131434140647400167630ustar00rootroot00000000000000//! A TCP server secured by TLS based on `async-native-tls`. //! //! First start a server: //! //! ``` //! cargo run --example tls-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example tls-client //! ``` use std::net::{TcpListener, TcpStream}; use anyhow::Result; use async_native_tls::{Identity, TlsAcceptor, TlsStream}; use smol::{io, Async}; /// Echoes messages from the client back to it. async fn echo(stream: TlsStream>) -> Result<()> { let stream = async_dup::Mutex::new(stream); io::copy(&stream, &mut &stream).await?; Ok(()) } fn main() -> Result<()> { // Initialize TLS with the local certificate, private key, and password. let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?; let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?); smol::block_on(async { // Create a listener. let listener = Async::::bind(([127, 0, 0, 1], 7001))?; println!("Listening on {}", listener.get_ref().local_addr()?); println!("Now start a TLS client."); // Accept clients in a loop. loop { let (stream, _) = listener.accept().await?; let stream = tls.accept(stream).await?; println!( "Accepted client: {}", stream.get_ref().get_ref().peer_addr()? ); // Spawn a task that echoes messages from the client back to it. smol::spawn(echo(stream)).detach(); } }) } smol-1.3.0/examples/unix-signal.rs000066400000000000000000000016261434140647400171230ustar00rootroot00000000000000//! Uses the `signal-hook` crate to catch the Ctrl-C signal. //! //! Run with: //! //! ``` //! cargo run --example unix-signal //! ``` #[cfg(unix)] fn main() -> std::io::Result<()> { use std::os::unix::{io::AsRawFd, net::UnixStream}; use smol::{prelude::*, Async}; smol::block_on(async { // Create a Unix stream that receives a byte on each signal occurrence. let (a, mut b) = Async::::pair()?; // Async isn't IntoRawFd, but it is AsRawFd, so let's pass the raw fd directly. signal_hook::low_level::pipe::register_raw(signal_hook::consts::SIGINT, a.as_raw_fd())?; println!("Waiting for Ctrl-C..."); // Receive a byte that indicates the Ctrl-C signal occurred. b.read_exact(&mut [0]).await?; println!("Done!"); Ok(()) }) } #[cfg(not(unix))] fn main() { println!("This example works only on Unix systems!"); } smol-1.3.0/examples/web-crawler.rs000066400000000000000000000046431434140647400171010ustar00rootroot00000000000000//! Crawls the Rust language website and prints found pages. //! //! Run with: //! //! ``` //! cargo run --example web-crawler //! ``` use std::collections::{HashSet, VecDeque}; use anyhow::Result; use async_channel::{bounded, Sender}; use scraper::{Html, Selector}; const ROOT: &str = "https://www.rust-lang.org"; /// Fetches the HTML contents of a web page. async fn fetch(url: String, sender: Sender) { let body = surf::get(&url).recv_string().await; let body = body.unwrap_or_default(); sender.send(body).await.ok(); } /// Extracts links from a HTML body. fn links(body: String) -> Vec { let mut v = Vec::new(); for elem in Html::parse_fragment(&body).select(&Selector::parse("a").unwrap()) { if let Some(link) = elem.value().attr("href") { v.push(link.to_string()); } } v } fn main() -> Result<()> { smol::block_on(async { let mut seen = HashSet::new(); let mut queue = VecDeque::new(); seen.insert(ROOT.to_string()); queue.push_back(ROOT.to_string()); let (s, r) = bounded(200); let mut tasks = 0; // Loop while the queue is not empty or tasks are fetching pages. while queue.len() + tasks > 0 { // Limit the number of concurrent tasks. while tasks < s.capacity().unwrap() { // Process URLs in the queue and fetch more pages. match queue.pop_front() { None => break, Some(url) => { println!("{}", url); tasks += 1; smol::spawn(fetch(url, s.clone())).detach(); } } } // Get a fetched web page. let body = r.recv().await.unwrap(); tasks -= 1; // Parse links in the web page and add them to the queue. for mut url in links(body) { // Add the site prefix if it's missing. if url.starts_with('/') { url = format!("{}{}", ROOT, url); } // If the URL makes sense and was not seen already, push it into the queue. if url.starts_with(ROOT) && seen.insert(url.clone()) { url = url.trim_end_matches('/').to_string(); queue.push_back(url); } } } Ok(()) }) } smol-1.3.0/examples/websocket-client.rs000066400000000000000000000103161434140647400201230ustar00rootroot00000000000000//! A WebSocket+TLS client based on `async-tungstenite` and `async-native-tls`. //! //! First start a server: //! //! ``` //! cargo run --example websocket-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example websocket-client //! ``` use std::net::{TcpStream, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::{bail, Context as _, Result}; use async_native_tls::{Certificate, TlsConnector, TlsStream}; use async_tungstenite::WebSocketStream; use futures::sink::{Sink, SinkExt}; use smol::{prelude::*, Async}; use tungstenite::handshake::client::Response; use tungstenite::Message; use url::Url; /// Connects to a WebSocket address (optionally secured by TLS). async fn connect(addr: &str, tls: TlsConnector) -> Result<(WsStream, Response)> { // Parse the address. let url = Url::parse(addr)?; let host = url.host_str().context("cannot parse host")?.to_string(); let port = url.port_or_known_default().context("cannot guess port")?; // Resolve the address. let socket_addr = { let host = host.clone(); smol::unblock(move || (host.as_str(), port).to_socket_addrs()) .await? .next() .context("cannot resolve address")? }; // Connect to the address. match url.scheme() { "ws" => { let stream = Async::::connect(socket_addr).await?; let (stream, resp) = async_tungstenite::client_async(addr, stream).await?; Ok((WsStream::Plain(stream), resp)) } "wss" => { // In case of WSS, establish a secure TLS connection first. let stream = Async::::connect(socket_addr).await?; let stream = tls.connect(host, stream).await?; let (stream, resp) = async_tungstenite::client_async(addr, stream).await?; Ok((WsStream::Tls(stream), resp)) } scheme => bail!("unsupported scheme: {}", scheme), } } fn main() -> Result<()> { // Initialize TLS with the local certificate. let mut builder = native_tls::TlsConnector::builder(); builder.add_root_certificate(Certificate::from_pem(include_bytes!("certificate.pem"))?); let tls = TlsConnector::from(builder); smol::block_on(async { // Connect to the server. let (mut stream, resp) = connect("wss://127.0.0.1:9001", tls).await?; dbg!(resp); // Send a message and receive a response. stream.send(Message::text("Hello!")).await?; dbg!(stream.next().await); Ok(()) }) } /// A WebSocket or WebSocket+TLS connection. enum WsStream { /// A plain WebSocket connection. Plain(WebSocketStream>), /// A WebSocket connection secured by TLS. Tls(WebSocketStream>>), } impl Sink for WsStream { type Error = tungstenite::Error; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_ready(cx), WsStream::Tls(s) => Pin::new(s).poll_ready(cx), } } fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> { match &mut *self { WsStream::Plain(s) => Pin::new(s).start_send(item), WsStream::Tls(s) => Pin::new(s).start_send(item), } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_flush(cx), WsStream::Tls(s) => Pin::new(s).poll_flush(cx), } } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_close(cx), WsStream::Tls(s) => Pin::new(s).poll_close(cx), } } } impl Stream for WsStream { type Item = tungstenite::Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_next(cx), WsStream::Tls(s) => Pin::new(s).poll_next(cx), } } } smol-1.3.0/examples/websocket-server.rs000066400000000000000000000102011434140647400201440ustar00rootroot00000000000000//! A WebSocket+TLS echo server based on `async-tungstenite` and `async-native-tls`. //! //! First start a server: //! //! ``` //! cargo run --example websocket-server //! ``` //! //! Then start a client: //! //! ``` //! cargo run --example websocket-client //! ``` use std::net::{TcpListener, TcpStream}; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::{Context as _, Result}; use async_native_tls::{Identity, TlsAcceptor, TlsStream}; use async_tungstenite::WebSocketStream; use futures::sink::{Sink, SinkExt}; use smol::{future, prelude::*, Async}; use tungstenite::Message; /// Echoes messages from the client back to it. async fn echo(mut stream: WsStream) -> Result<()> { let msg = stream.next().await.context("expected a message")??; stream.send(Message::text(msg.to_string())).await?; Ok(()) } /// Listens for incoming connections and serves them. async fn listen(listener: Async, tls: Option) -> Result<()> { let host = match &tls { None => format!("ws://{}", listener.get_ref().local_addr()?), Some(_) => format!("wss://{}", listener.get_ref().local_addr()?), }; println!("Listening on {}", host); loop { // Accept the next connection. let (stream, _) = listener.accept().await?; println!("Accepted client: {}", stream.get_ref().peer_addr()?); match &tls { None => { let stream = WsStream::Plain(async_tungstenite::accept_async(stream).await?); smol::spawn(echo(stream)).detach(); } Some(tls) => { // In case of WSS, establish a secure TLS connection first. let stream = tls.accept(stream).await?; let stream = WsStream::Tls(async_tungstenite::accept_async(stream).await?); smol::spawn(echo(stream)).detach(); } } } } fn main() -> Result<()> { // Initialize TLS with the local certificate, private key, and password. let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?; let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?); // Start WS and WSS servers. smol::block_on(async { let ws = listen(Async::::bind(([127, 0, 0, 1], 9000))?, None); let wss = listen( Async::::bind(([127, 0, 0, 1], 9001))?, Some(tls), ); future::try_zip(ws, wss).await?; Ok(()) }) } /// A WebSocket or WebSocket+TLS connection. enum WsStream { /// A plain WebSocket connection. Plain(WebSocketStream>), /// A WebSocket connection secured by TLS. Tls(WebSocketStream>>), } impl Sink for WsStream { type Error = tungstenite::Error; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_ready(cx), WsStream::Tls(s) => Pin::new(s).poll_ready(cx), } } fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> { match &mut *self { WsStream::Plain(s) => Pin::new(s).start_send(item), WsStream::Tls(s) => Pin::new(s).start_send(item), } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_flush(cx), WsStream::Tls(s) => Pin::new(s).poll_flush(cx), } } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_close(cx), WsStream::Tls(s) => Pin::new(s).poll_close(cx), } } } impl Stream for WsStream { type Item = tungstenite::Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match &mut *self { WsStream::Plain(s) => Pin::new(s).poll_next(cx), WsStream::Tls(s) => Pin::new(s).poll_next(cx), } } } smol-1.3.0/examples/windows-uds.rs000066400000000000000000000027131434140647400171460ustar00rootroot00000000000000//! Uses the `uds_windows` crate to simulate Unix sockets on Windows. //! //! Run with: //! //! ``` //! cargo run --example windows-uds //! ``` #[cfg(windows)] fn main() -> std::io::Result<()> { use std::path::PathBuf; use smol::{io, prelude::*, Async, Unblock}; use tempfile::tempdir; use uds_windows::{UnixListener, UnixStream}; async fn client(addr: PathBuf) -> io::Result<()> { // Connect to the address. let stream = Async::new(UnixStream::connect(addr)?)?; println!("Connected to {:?}", stream.get_ref().peer_addr()?); // Pipe the stream to stdout. let mut stdout = Unblock::new(std::io::stdout()); io::copy(&stream, &mut stdout).await?; Ok(()) } let dir = tempdir()?; let path = dir.path().join("socket"); smol::block_on(async { // Create a listener. let listener = Async::new(UnixListener::bind(&path)?)?; println!("Listening on {:?}", listener.get_ref().local_addr()?); // Spawn a client task. let task = smol::spawn(client(path)); // Accept the client. let (stream, _) = listener.read_with(|l| l.accept()).await?; println!("Accepted a client"); // Send a message, drop the stream, and wait for the client. Async::new(stream)?.write_all(b"Hello!\n").await?; task.await?; Ok(()) }) } #[cfg(not(windows))] fn main() { println!("This example works only on Windows!"); } smol-1.3.0/src/000077500000000000000000000000001434140647400132635ustar00rootroot00000000000000smol-1.3.0/src/lib.rs000066400000000000000000000032011434140647400143730ustar00rootroot00000000000000//! A small and fast async runtime. //! //! This crate simply re-exports other smaller async crates (see the source). //! //! To use tokio-based libraries with smol, apply the [`async-compat`] adapter to futures and I/O //! types. //! //! # Examples //! //! Connect to an HTTP website, make a GET request, and pipe the response to the standard output: //! //! ``` //! use smol::{io, net, prelude::*, Unblock}; //! //! fn main() -> io::Result<()> { //! smol::block_on(async { //! let mut stream = net::TcpStream::connect("example.com:80").await?; //! let req = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"; //! stream.write_all(req).await?; //! //! let mut stdout = Unblock::new(std::io::stdout()); //! io::copy(stream, &mut stdout).await?; //! Ok(()) //! }) //! } //! ``` //! //! There's a lot more in the [examples] directory. //! //! [`async-compat`]: https://docs.rs/async-compat //! [examples]: https://github.com/smol-rs/smol/tree/master/examples //! [get-request]: https://github.com/smol-rs/smol/blob/master/examples/get-request.rs #![forbid(unsafe_code)] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #[cfg(doctest)] doc_comment::doctest!("../README.md"); #[doc(inline)] pub use { async_executor::{Executor, LocalExecutor, Task}, async_io::{block_on, Async, Timer}, blocking::{unblock, Unblock}, futures_lite::{future, io, pin, prelude, ready, stream}, }; #[doc(inline)] pub use { async_channel as channel, async_fs as fs, async_lock as lock, async_net as net, async_process as process, }; mod spawn; pub use spawn::spawn; smol-1.3.0/src/spawn.rs000066400000000000000000000034051434140647400147630ustar00rootroot00000000000000use std::future::Future; use std::panic::catch_unwind; use std::thread; use async_executor::{Executor, Task}; use async_io::block_on; use async_lock::OnceCell; use futures_lite::future; /// Spawns a task onto the global executor (single-threaded by default). /// /// There is a global executor that gets lazily initialized on first use. It is included in this /// library for convenience when writing unit tests and small programs, but it is otherwise /// more advisable to create your own [`Executor`]. /// /// By default, the global executor is run by a single background thread, but you can also /// configure the number of threads by setting the `SMOL_THREADS` environment variable. /// /// # Examples /// /// ``` /// let task = smol::spawn(async { /// 1 + 2 /// }); /// /// smol::block_on(async { /// assert_eq!(task.await, 3); /// }); /// ``` pub fn spawn(future: impl Future + Send + 'static) -> Task { static GLOBAL: OnceCell> = OnceCell::new(); fn global() -> &'static Executor<'static> { GLOBAL.get_or_init_blocking(|| { let num_threads = { // Parse SMOL_THREADS or default to 1. std::env::var("SMOL_THREADS") .ok() .and_then(|s| s.parse().ok()) .unwrap_or(1) }; for n in 1..=num_threads { thread::Builder::new() .name(format!("smol-{}", n)) .spawn(|| loop { catch_unwind(|| block_on(global().run(future::pending::<()>()))).ok(); }) .expect("cannot spawn executor thread"); } Executor::new() }) } global().spawn(future) }