Compare commits

...

90 Commits

Author SHA1 Message Date
dependabot[bot] 641326b54f Update http requirement from 0.2 to 1.1
Updates the requirements on [http](https://github.com/hyperium/http) to permit the latest version.
- [Release notes](https://github.com/hyperium/http/releases)
- [Changelog](https://github.com/hyperium/http/blob/master/CHANGELOG.md)
- [Commits](https://github.com/hyperium/http/compare/v0.2.0...v1.1.0)

---
updated-dependencies:
- dependency-name: http
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 07:30:05 -07:00
dependabot[bot] bc7a85d170 Update scraper requirement from 0.18 to 0.19
Updates the requirements on [scraper](https://github.com/causal-agent/scraper) to permit the latest version.
- [Release notes](https://github.com/causal-agent/scraper/releases)
- [Commits](https://github.com/causal-agent/scraper/compare/v0.18.0...v0.19.0)

---
updated-dependencies:
- dependency-name: scraper
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-04 23:17:49 +09:00
dependabot[bot] f8f5a4af67 Update async-tungstenite requirement from 0.24 to 0.25
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.24.0...0.25.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-12 06:25:23 -08:00
John Nunley 490c4c6e64 ex: Use smol-hyper in hyper-server example
Signed-off-by: John Nunley <dev@notgull.net>
2024-01-15 17:54:46 -08:00
John Nunley f3054c3537 ex: Use smol-hyper in hyper-client example
Signed-off-by: John Nunley <dev@notgull.net>
2024-01-15 17:54:46 -08:00
John Nunley 5b505fc26d
docs: Add link to Matrix chat to README
This should hopefully improve discovery for our Matrix chatroom.

Signed-off-by: John Nunley <dev@notgull.net>
2024-01-15 17:40:30 -08:00
John Nunley d37bf58d8d
v2.0.0
Signed-off-by: John Nunley <dev@notgull.net>
2023-12-31 10:42:28 -08:00
dependabot[bot] b1c9f8743e Update async-tungstenite requirement from 0.23 to 0.24
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.23.0...0.24.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-11 22:44:06 +09:00
dependabot[bot] bdc061956a Update scraper requirement from 0.17 to 0.18
Updates the requirements on [scraper](https://github.com/causal-agent/scraper) to permit the latest version.
- [Release notes](https://github.com/causal-agent/scraper/releases)
- [Commits](https://github.com/causal-agent/scraper/compare/v0.17.0...v0.18.1)

---
updated-dependencies:
- dependency-name: scraper
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-06 22:59:53 +09:00
John Nunley 75c8dcedfa Run the process driver on the executor thread
This allows us to avoid spawning an additional thread in some cases.

Signed-off-by: John Nunley <dev@notgull.net>
2023-11-02 06:38:41 -07:00
John Nunley 19ca79660f
breaking: Bump all subcrates to their newest versions
This is a breaking change.

Signed-off-by: John Nunley <dev@notgull.net>
2023-11-01 19:30:30 -07:00
dependabot[bot] f337143aba Update async-fs requirement from 1.3.0 to 2.0.0
Updates the requirements on [async-fs](https://github.com/smol-rs/async-fs) to permit the latest version.
- [Release notes](https://github.com/smol-rs/async-fs/releases)
- [Changelog](https://github.com/smol-rs/async-fs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/async-fs/compare/v1.3.0...v2.0.0)

---
updated-dependencies:
- dependency-name: async-fs
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-31 01:27:36 +09:00
dependabot[bot] 19a6a3faaa Update async-lock requirement from 2.6.0 to 3.0.0
Updates the requirements on [async-lock](https://github.com/smol-rs/async-lock) to permit the latest version.
- [Release notes](https://github.com/smol-rs/async-lock/releases)
- [Changelog](https://github.com/smol-rs/async-lock/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/async-lock/compare/v2.6.0...v3.0.0)

---
updated-dependencies:
- dependency-name: async-lock
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-31 00:52:01 +09:00
dependabot[bot] 1beb26f5d1 Update async-channel requirement from 1.4.2 to 2.0.0
Updates the requirements on [async-channel](https://github.com/smol-rs/async-channel) to permit the latest version.
- [Release notes](https://github.com/smol-rs/async-channel/releases)
- [Changelog](https://github.com/smol-rs/async-channel/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/async-channel/compare/v1.4.2...v2.0.0)

---
updated-dependencies:
- dependency-name: async-channel
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-31 00:44:11 +09:00
dependabot[bot] d1da833155 Update async-net requirement from 1.4.3 to 2.0.0
Updates the requirements on [async-net](https://github.com/smol-rs/async-net) to permit the latest version.
- [Release notes](https://github.com/smol-rs/async-net/releases)
- [Changelog](https://github.com/smol-rs/async-net/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/async-net/compare/v1.4.3...v2.0.0)

---
updated-dependencies:
- dependency-name: async-net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-31 00:43:37 +09:00
Alex Touchet f0cd8e37d9
docs: Fix build badge 2023-10-18 05:47:03 -07:00
Taiki Endo 8d8879df0f Update actions/checkout action to v4 2023-09-10 18:28:30 +09:00
Taiki Endo 7e95fff0bf Use rustix in linux-timerfd example 2023-08-30 01:53:44 +09:00
John Nunley 86dad666a1
Merge pull request #262 from esp-rs-compat/espidf 2023-08-29 07:09:15 -07:00
dependabot[bot] 2ca5cd505b Update nix requirement from 0.26 to 0.27
Updates the requirements on [nix](https://github.com/nix-rust/nix) to permit the latest version.
- [Changelog](https://github.com/nix-rust/nix/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nix-rust/nix/compare/v0.26.0...v0.27.0)

---
updated-dependencies:
- dependency-name: nix
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-28 22:47:06 +09:00
imarkov 5d51de0bd5 Support for the ESP-IDF framework 2023-08-18 07:11:34 +00:00
dependabot[bot] 084a207cf1 Update async-tungstenite requirement from 0.22 to 0.23
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.22.0...0.23.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-14 23:03:27 +09:00
Taiki Endo 8a67449e06 Remove tungstenite dev-dependency
Use re-export from async-tungstenite.
2023-08-06 16:41:08 +09:00
Taiki Endo c428a2b225 Bump MSRV to 1.63
rustix 0.38 and the next version of many io-related async-* crates
require Rust 1.63.
2023-08-06 16:06:53 +09:00
John Nunley 35b45aa3da
docs: Use the new smol logo in docs and README 2023-07-16 07:22:16 -07:00
dependabot[bot] 14d27a94c5 Update scraper requirement from 0.16 to 0.17
Updates the requirements on [scraper](https://github.com/causal-agent/scraper) to permit the latest version.
- [Release notes](https://github.com/causal-agent/scraper/releases)
- [Commits](https://github.com/causal-agent/scraper/compare/v0.16.0...v0.17.1)

---
updated-dependencies:
- dependency-name: scraper
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 23:02:47 +09:00
Taiki Endo 4604978cf0 Fix deprecated warning in example
```
error: use of deprecated method `inotify::Inotify::add_watch`: use `Inotify.watches().add()` instead
  --> examples/linux-inotify.rs:38:27
   |
38 |         inotify.get_mut().add_watch(".", WatchMask::ALL_EVENTS)?;
   |                           ^^^^^^^^^
   |
   = note: `-D deprecated` implied by `-D warnings`
```
2023-06-11 18:04:49 +09:00
dependabot[bot] b35cafc04b Update async-tungstenite requirement from 0.21 to 0.22
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Release notes](https://github.com/sdroege/async-tungstenite/releases)
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.21.0...0.22.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 23:18:59 +09:00
Taiki Endo ef89385fcb Update tungstenite to 0.19, async-tungstenite to 0.21 2023-04-21 01:26:41 +09:00
dependabot[bot] 5ceeb1598b
Update scraper requirement from 0.15 to 0.16 (#253) 2023-04-10 08:15:51 -07:00
Taiki Endo bf64d51914 Update permissions for security_audit 2023-03-07 00:18:36 +09:00
dependabot[bot] b2a51bb937 Update async-native-tls requirement from 0.4 to 0.5
Updates the requirements on [async-native-tls](https://github.com/async-email/async-native-tls) to permit the latest version.
- [Release notes](https://github.com/async-email/async-native-tls/releases)
- [Commits](https://github.com/async-email/async-native-tls/compare/v0.4.0...v0.5.0)

---
updated-dependencies:
- dependency-name: async-native-tls
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-06 23:41:24 +09:00
dependabot[bot] 678f70de25 Update scraper requirement from 0.14 to 0.15
Updates the requirements on [scraper](https://github.com/causal-agent/scraper) to permit the latest version.
- [Release notes](https://github.com/causal-agent/scraper/releases)
- [Commits](https://github.com/causal-agent/scraper/compare/v0.14.0...v0.15.0)

---
updated-dependencies:
- dependency-name: scraper
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-06 23:29:07 +09:00
Taiki Endo c65906cac8 Bump MSRV to 1.48
async-lock 2.7.0 requires Rust 1.48.

```
error[E0658]: use of unstable library feature 'future_readiness_fns'
   --> /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/async-lock-2.7.0/src/once_cell.rs:430:45
    |
430 |             self.initialize_or_wait(move || std::future::ready(closure()), &mut Blocking),
    |                                             ^^^^^^^^^^^^^^^^^^
    |
```
2023-03-06 01:47:28 +09:00
Taiki Endo b2a5e69394 Minimize GITHUB_TOKEN permissions
Refs: https://github.blog/changelog/2021-04-20-github-actions-control-permissions-for-github_token
2023-03-04 11:41:39 +09:00
Taiki Endo be21c2f968 Set CARGO_NET_GIT_FETCH_WITH_CLI=true in CI 2023-03-04 11:41:39 +09:00
dependabot[bot] 9e13aecceb Update async-tungstenite requirement from 0.19 to 0.20
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Release notes](https://github.com/sdroege/async-tungstenite/releases)
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.19.0...0.20.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-13 23:23:50 +09:00
John Nunley 36e085f9fa
Add an official MSRV policy (#243) 2023-01-15 11:42:17 +09:00
dependabot[bot] f5c45807c2 Update async-tungstenite requirement from 0.17 to 0.19
Updates the requirements on [async-tungstenite](https://github.com/sdroege/async-tungstenite) to permit the latest version.
- [Release notes](https://github.com/sdroege/async-tungstenite/releases)
- [Changelog](https://github.com/sdroege/async-tungstenite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sdroege/async-tungstenite/compare/0.17.0...0.19.0)

---
updated-dependencies:
- dependency-name: async-tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-30 15:18:01 +09:00
dependabot[bot] faee9a8ca5 Update tungstenite requirement from 0.17 to 0.18
Updates the requirements on [tungstenite](https://github.com/snapview/tungstenite-rs) to permit the latest version.
- [Release notes](https://github.com/snapview/tungstenite-rs/releases)
- [Changelog](https://github.com/snapview/tungstenite-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/snapview/tungstenite-rs/compare/v0.17.0...v0.18.0)

---
updated-dependencies:
- dependency-name: tungstenite
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-30 15:18:01 +09:00
dependabot[bot] 0ae00dac77 Update nix requirement from 0.24 to 0.26
Updates the requirements on [nix](https://github.com/nix-rust/nix) to permit the latest version.
- [Release notes](https://github.com/nix-rust/nix/releases)
- [Changelog](https://github.com/nix-rust/nix/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nix-rust/nix/compare/v0.24.0...v0.26.1)

---
updated-dependencies:
- dependency-name: nix
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-28 12:50:31 +09:00
dependabot[bot] fc6acf23c9 Update scraper requirement from 0.13 to 0.14
Updates the requirements on [scraper](https://github.com/causal-agent/scraper) to permit the latest version.
- [Release notes](https://github.com/causal-agent/scraper/releases)
- [Commits](https://github.com/causal-agent/scraper/compare/v0.13.0...v0.14.0)

---
updated-dependencies:
- dependency-name: scraper
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-28 12:46:24 +09:00
Taiki Endo 4b16219609 Enable dependabot update for Rust 2022-12-28 12:25:47 +09:00
Taiki Endo 3022d23f27 Clean up CI config 2022-12-28 12:25:47 +09:00
Taiki Endo 29a075db59 Release 1.3.0 2022-11-29 22:46:36 +09:00
Taiki Endo 10a00cff81 Remove msrv field from .clippy.toml
Since Rust 1.64, Clippy respects `rust-version` field in Cargo.toml.
rust-lang/rust@b776fb8
2022-11-29 22:46:36 +09:00
John Nunley 8e97a4477e
Replace once-cell with async-lock (#241)
* Replace once-cell with async-lock

* Update dependencies
2022-11-27 20:39:36 -08:00
Taiki Endo 78d512a277 Ignore clippy::type_complexity lint in example
```
warning: very complex type used. Consider factoring parts into `type` definitions
   --> examples/hyper-server.rs:132:15
    |
132 |     Handshake(Pin<Box<dyn Future<Output = io::Result<TlsStream<Async<TcpStream>>>> + Send>>),
    |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: `#[warn(clippy::type_complexity)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity
```
2022-07-17 21:26:29 +09:00
Taiki Endo 9699af3649 Fix clippy::unused_unit warning in examples
```
warning: unneeded unit expression
   --> examples/hyper-client.rs:139:25
    |
139 |                         ()
    |                         ^^ help: remove the final `()`
    |
    = note: `#[warn(clippy::unused_unit)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit

warning: unneeded unit expression
   --> examples/hyper-client.rs:147:25
    |
147 |                         ()
    |                         ^^ help: remove the final `()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit

warning: unneeded unit expression
   --> examples/hyper-server.rs:154:29
    |
154 | ...                   ()
    |                       ^^ help: remove the final `()`
    |
    = note: `#[warn(clippy::unused_unit)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit

warning: unneeded unit expression
   --> examples/hyper-server.rs:162:29
    |
162 | ...                   ()
    |                       ^^ help: remove the final `()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit
```
2022-07-17 21:25:23 +09:00
Taiki Endo 534ac48a01 Apply clippy to all targets 2022-07-17 21:22:12 +09:00
Taiki Endo 31c3582ef5
Update dependencies (#239) 2022-07-08 02:16:10 +09:00
Taiki Endo 38bf6dc05e Bump MSRV to Rust 1.47
https://github.com/smol-rs/async-task/releases/tag/v4.3.0
2022-07-08 01:51:58 +09:00
Taiki Endo 2c78616547 Update CI config 2022-07-08 01:51:12 +09:00
Taiki Endo 473ca3cb3b Update actions/checkout action to v3 2022-05-01 14:47:31 +09:00
Taiki Endo c2f5bfcd61
Merge pull request #231 from smol-rs/deps
Update dev-dependencies
2022-01-09 01:23:58 +09:00
Taiki Endo 08f027b9b5 Update dev-dependencies 2022-01-09 01:15:27 +09:00
Taiki Endo 404c7bcc0a Remove rustfmt.toml 2022-01-09 01:15:08 +09:00
Taiki Endo 953620d52b Create GitHub release automatically 2022-01-09 01:05:11 +09:00
Taiki Endo fb0d263f71 Clean up CI config 2022-01-09 01:04:47 +09:00
Taiki Endo 440c224b49
Merge pull request #229 from smol-rs/deps
Update dev-dependencies
2021-06-30 23:38:58 +09:00
Taiki Endo c210c4033a Update dev-dependencies 2021-06-30 23:28:19 +09:00
Taiki Endo ad0839e1b3
Merge pull request #227 from smol-rs/hyper-example
Fix hyper-server example
2021-02-14 21:09:15 +09:00
Taiki Endo 95cc5842dc
Merge pull request #226 from smol-rs/readme
Remove readme field from Cargo.toml
2021-02-14 21:09:04 +09:00
Taiki Endo 4bed635df7
Merge pull request #224 from smol-rs/badge
Update license badge to match Cargo.toml
2021-02-14 21:00:36 +09:00
Taiki Endo 90891b0305 Fix hyper-server example 2021-02-14 20:53:00 +09:00
Taiki Endo ba1f3d2c69 Remove readme field from Cargo.toml 2021-02-14 20:49:54 +09:00
Taiki Endo 2526bf7d80 Update license badge to match Cargo.toml 2021-02-14 20:49:21 +09:00
Taiki Endo f8bebeb348
Merge pull request #225 from smol-rs/surf
Temporarily disable example that using surf
2021-02-14 20:48:05 +09:00
Taiki Endo 9a0bed4273 Temporarily disable example that using surf 2021-02-14 20:25:19 +09:00
Taiki Endo 76dac2a493
Merge pull request #218 from nickbp/master
Bump dev-dependencies for examples
2021-01-21 12:22:50 +09:00
Nick Parker 79e577a919 Update surf and any recently updated dev-dependencies 2021-01-21 11:28:52 +13:00
Nick Parker 5f7c474431 Bump dev-dependencies for examples
Updates the dependencies used by examples to current - some have had API-breaking changes, so some examples are updated to catch up with those as well.

Note that the hyper-server example doesn't seem to work when tested, but it also didn't work before this PR. Looked at it a bit and found that poll_accept() returns Pending via incoming.poll_next() and then poll_accept() isn't invoked again. hyper-client meanwhile works fine, so the issue doesn't seem to be related to the AsyncRead updates.
2021-01-04 23:56:16 +13:00
Taiki Endo f4eea3133f
Merge pull request #215 from atouchet/url
Update URLs
2020-12-26 21:27:45 +09:00
Taiki Endo 9060e0f247
Merge pull request #216 from taiki-e/ci
Remove CURRENT_WEEK environment variable
2020-12-24 18:12:52 +09:00
Taiki Endo a5ae0afa2b Remove CURRENT_WEEK environment variable 2020-12-24 17:57:13 +09:00
atouchet b1dbdc00f9 Update URLs 2020-12-23 12:31:12 -08:00
Stjepan Glavina 9a1ad8d2ba
. 2020-11-30 12:31:16 +01:00
Stjepan Glavina ea4dec080b Bump to v1.2.5 2020-11-28 21:45:58 +01:00
Stjepan Glavina 77998a9f0a Fix CI 2020-11-28 21:44:08 +01:00
Stjepan Glavina f7d0eba792
Update README.md 2020-10-14 23:48:24 +02:00
Stjepan Glavina bf7294ca8d Bump to v1.2.4 2020-10-09 14:17:23 +02:00
Stjepan Glavina 15447d6859 Refactor 2020-10-09 14:16:52 +02:00
Stjepan Glavina eb656a98f4 Bump to v1.2.3 2020-10-04 14:32:03 +02:00
Stjepan Glavina e9a34a74d8 Bump top v1.2.2 2020-09-28 12:38:18 +02:00
Stjepan Glavina cf640bb877 Revert 2020-09-21 19:13:45 +02:00
Stjepan Glavina 4fa527985b Fix CI 2020-09-21 19:10:41 +02:00
Stjepan Glavina aa980f48e8 Bump to v1.2.1 2020-09-21 19:07:01 +02:00
Stjepan Glavina 9d3b1db1f4 Bump to v1.2.0 2020-09-21 12:51:00 +02:00
Stjepan Glavina 276cf1c6be Upgrade dependencies 2020-09-21 12:50:41 +02:00
Stjepan Glavina 7942ced667 Docs 2020-09-21 11:15:55 +02:00
23 changed files with 592 additions and 512 deletions

1
.github/FUNDING.yml vendored
View File

@ -1 +0,0 @@
github: stjepang

9
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,9 @@
version: 2
updates:
- package-ecosystem: cargo
directory: /
schedule:
interval: weekly
commit-message:
prefix: ''
labels: []

View File

@ -1,59 +0,0 @@
name: Build and test
on:
push:
branches:
- master
pull_request:
jobs:
build_and_test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
rust: [nightly, beta, stable, 1.39.0]
steps:
- uses: actions/checkout@v2
- name: Set current week of the year in environnement
if: startsWith(matrix.os, 'ubuntu') || startsWith(matrix.os, 'macOS')
run: echo "::set-env name=CURRENT_WEEK::$(date +%V)"
- name: Set current week of the year in environnement
if: startsWith(matrix.os, 'windows')
run: echo "::set-env name=CURRENT_WEEK::$(Get-Date -UFormat %V)"
- name: Install latest ${{ matrix.rust }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
profile: minimal
override: true
- name: Run basic cargo check
uses: actions-rs/cargo@v1
with:
command: check
args: --all --bins --all-features
- name: Run cargo check
if: startsWith(matrix.rust, '1.39.0') == false
uses: actions-rs/cargo@v1
with:
command: check
args: --all --benches --bins --examples --tests --all-features
- name: Run cargo check (without dev-dependencies to catch missing feature flags)
if: startsWith(matrix.rust, 'nightly')
uses: actions-rs/cargo@v1
with:
command: check
args: -Z features=dev_dep
- name: Run cargo test
if: startsWith(matrix.rust, '1.39.0') == false
uses: actions-rs/cargo@v1
with:
command: test

87
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,87 @@
name: CI
permissions:
contents: read
on:
pull_request:
push:
branches:
- master
schedule:
- cron: '0 2 * * 0'
env:
CARGO_INCREMENTAL: 0
CARGO_NET_GIT_FETCH_WITH_CLI: true
CARGO_NET_RETRY: 10
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
RUSTFLAGS: -D warnings
RUSTDOCFLAGS: -D warnings
RUSTUP_MAX_RETRIES: 10
defaults:
run:
shell: bash
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@v4
- 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 and README.md.
rust: ['1.63']
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }}
- run: cargo build
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: rustup update stable
- run: cargo clippy --all-features --all-targets
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: rustup update stable
- run: cargo fmt --all --check
security_audit:
permissions:
checks: write
contents: read
issues: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# https://github.com/rustsec/audit-check/issues/2
- uses: rustsec/audit-check@master
with:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,27 +0,0 @@
name: Lint
on:
push:
branches:
- master
pull_request:
jobs:
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set current week of the year in environnement
run: echo "::set-env name=CURRENT_WEEK::$(date +%V)"
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
components: clippy
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features -- -W clippy::all

22
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: Release
permissions:
contents: write
on:
push:
tags:
- v[0-9]+.*
jobs:
create-release:
if: github.repository_owner == 'smol-rs'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: taiki-e/create-gh-release-action@v1
with:
changelog: CHANGELOG.md
branch: master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,20 +0,0 @@
name: Security audit
on:
push:
branches:
- master
pull_request:
jobs:
security_audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set current week of the year in environnement
run: echo "::set-env name=CURRENT_WEEK::$(date +%V)"
- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,3 +1,36 @@
# Version 2.0.0
- **Breaking:** Bump subcrates to their newest major versions. (#277, #280, #281, #282, #283)
- Run the `async-process` driver on the executor. (#284)
# 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`.

View File

@ -1,58 +1,60 @@
[package]
name = "smol"
version = "1.1.0"
# When publishing a new version:
# - Update CHANGELOG.md
# - Create "v2.x.y" git tag
version = "2.0.0"
authors = ["Stjepan Glavina <stjepang@gmail.com>"]
edition = "2018"
rust-version = "1.63"
description = "A small and fast async runtime"
license = "Apache-2.0 OR MIT"
repository = "https://github.com/stjepang/smol"
homepage = "https://github.com/stjepang/smol"
documentation = "https://docs.rs/smol"
repository = "https://github.com/smol-rs/smol"
keywords = ["async", "await", "future", "io", "networking"]
categories = ["asynchronous", "concurrency", "network-programming"]
readme = "README.md"
exclude = ["/.*"]
[dependencies]
async-channel = "1.4.2"
async-executor = "1.3.0"
async-fs = "1.3.0"
async-io = "1.1.0"
async-lock = "2.1.2"
async-net = "1.4.1"
async-process = "1.0.0"
blocking = "1.0.0"
futures-lite = "1.4.0"
once_cell = "1.4.1"
async-channel = "2.0.0"
async-executor = "1.5.0"
async-fs = "2.0.0"
async-io = "2.1.0"
async-lock = "3.0.0"
async-net = "2.0.0"
blocking = "1.3.0"
futures-lite = "2.0.0"
[target.'cfg(not(target_os = "espidf"))'.dependencies]
async-process = "2.0.0"
[dev-dependencies]
anyhow = "1.0.32"
async-dup = "1.2.1"
async-h1 = "2.1.2"
async-native-tls = "0.3.3"
async-std = "1.6.3"
async-tungstenite = { version = "0.8.0", features = ["async-native-tls"] }
base64 = "0.12.3"
ctrlc = "3.1.6"
doc-comment = "0.3.3"
futures = "0.3.5"
http = "0.2.1"
http-types = "2.4.0"
hyper = { version = "0.13.7", default-features = false, features = ["stream"] }
native-tls = "0.2.4"
num_cpus = "1.13.0"
scraper = "0.12.0"
signal-hook = "0.1.16"
surf = { version = "2.0.0-alpha.5", default-features = false, features = ["h1-client"] }
tempfile = "3.1.0"
tide = "0.13.0"
tokio = { version = "0.2.22", default-features = false, features = ["rt-threaded"] }
tungstenite = "0.11.1"
url = "2.1.1"
anyhow = "1"
async-dup = "1"
async-h1 = "2"
async-native-tls = "0.5"
async-tungstenite = { version = "0.25", features = ["async-native-tls"] }
ctrlc = "3"
doc-comment = "0.3"
futures = "0.3"
http = "1.1"
http-body-util = "0.1.0"
http-types = "2"
hyper = { version = "1.0", default-features = false, features = ["client", "http1", "server"] }
macro_rules_attribute = "0.2.0"
native-tls = "0.2"
scraper = "0.19"
signal-hook = "0.3"
smol-hyper = "0.1.0"
smol-macros = "0.1.0"
surf = { version = "2", default-features = false, features = ["h1-client"] }
tempfile = "3"
tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] }
url = "2"
[target.'cfg(target_os = "linux")'.dev-dependencies]
inotify = { version = "0.8.3", default-features = false }
nix = "0.18.0"
timerfd = "1.1.1"
inotify = { version = "0.10", default-features = false }
rustix = "0.38"
timerfd = "1"
[target.'cfg(windows)'.dev-dependencies]
uds_windows = "0.1.5"
uds_windows = "1"

View File

@ -1,15 +1,17 @@
# smol
[![Build](https://github.com/stjepang/smol/workflows/Build%20and%20test/badge.svg)](
https://github.com/stjepang/smol/actions)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](
https://github.com/stjepang/smol)
[![Build](https://github.com/smol-rs/smol/actions/workflows/ci.yml/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)
[![Chat](https://img.shields.io/matrix/smol-rs%3Amatrix.org)](
https://matrix.to/#/#smol-rs:matrix.org)
<img src="https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" alt="kitty" width="100px" style="float: left;" />
A small and fast async runtime.
@ -41,8 +43,40 @@ fn main() -> io::Result<()> {
There's a lot more in the [examples] directory.
[`async-compat`]: https://docs.rs/async-compat
[examples]: https://github.com/stjepang/smol/tree/master/examples
[get-request]: https://github.com/stjepang/smol/blob/master/examples/get-request.rs
[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
@ -67,6 +101,10 @@ Another useful tool for making certificates is [mkcert].
[mkcert]: https://github.com/FiloSottile/mkcert
## MSRV Policy
The Minimum Supported Rust Version (MSRV) of this crate is **1.63**. As a **tentative** policy, the MSRV will not advance past the [current Rust version provided by Debian Stable](https://packages.debian.org/stable/rust/rustc). At the time of writing, this version of Rust is *1.63*. However, the MSRV may be advanced further in the event of a major ecosystem shift or a security vulnerability.
## License
Licensed under either of

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

View File

@ -6,163 +6,139 @@
//! cargo run --example hyper-client
//! ```
use std::net::Shutdown;
use std::net::{TcpStream, ToSocketAddrs};
use std::convert::TryInto;
use std::pin::Pin;
use std::task::{Context, Poll};
use anyhow::{bail, Context as _, Error, Result};
use anyhow::{bail, Context as _, Result};
use async_native_tls::TlsStream;
use http::Uri;
use hyper::{Body, Client, Request, Response};
use smol::{io, prelude::*, Async};
use http_body_util::{BodyStream, Empty};
use hyper::body::Incoming;
use hyper::{Request, Response};
use macro_rules_attribute::apply;
use smol::{io, net::TcpStream, prelude::*, Executor};
use smol_hyper::rt::FuturesIo;
use smol_macros::main;
/// Sends a request and fetches the response.
async fn fetch(req: Request<Body>) -> Result<Response<Body>> {
Ok(Client::builder()
.executor(SmolExecutor)
.build::<_, Body>(SmolConnector)
.request(req)
.await?)
}
async fn fetch(
ex: &Executor<'static>,
req: Request<Empty<&'static [u8]>>,
) -> Result<Response<Incoming>> {
// Connect to the HTTP server.
let io = {
let host = req.uri().host().context("cannot parse host")?;
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<F: Future + Send + 'static> hyper::rt::Executor<F> 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<Uri> for SmolConnector {
type Response = SmolStream;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
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::<TcpStream>::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::<TcpStream>::connect(socket_addr).await?;
let stream = async_native_tls::connect(host, stream).await?;
Ok(SmolStream::Tls(stream))
}
scheme => bail!("unsupported scheme: {:?}", scheme),
match req.uri().scheme_str() {
Some("http") => {
let stream = {
let port = req.uri().port_u16().unwrap_or(80);
TcpStream::connect((host, port)).await?
};
SmolStream::Plain(stream)
}
Some("https") => {
// In case of HTTPS, establish a secure TLS connection first.
let stream = {
let port = req.uri().port_u16().unwrap_or(443);
TcpStream::connect((host, port)).await?
};
let stream = async_native_tls::connect(host, stream).await?;
SmolStream::Tls(stream)
}
scheme => bail!("unsupported scheme: {:?}", scheme),
}
};
// Spawn the HTTP/1 connection.
let (mut sender, conn) = hyper::client::conn::http1::handshake(FuturesIo::new(io)).await?;
ex.spawn(async move {
if let Err(e) = conn.await {
println!("Connection failed: {:?}", e);
}
})
.detach();
// Get the result
let result = sender.send_request(req).await?;
Ok(result)
}
#[apply(main!)]
async fn main(ex: &Executor<'static>) -> Result<()> {
// Create a request.
let url: hyper::Uri = "https://www.rust-lang.org".try_into()?;
let req = Request::builder()
.header(
hyper::header::HOST,
url.authority().unwrap().clone().as_str(),
)
.uri(url)
.body(Empty::new())?;
// Fetch the response.
let resp = fetch(ex, req).await?;
println!("{:#?}", resp);
// Read the message body.
let body: Vec<u8> = BodyStream::new(resp.into_body())
.try_fold(Vec::new(), |mut body, chunk| {
if let Some(chunk) = chunk.data_ref() {
body.extend_from_slice(chunk);
}
Ok(body)
})
}
.await?;
println!("{}", String::from_utf8_lossy(&body));
Ok(())
}
/// A TCP or TCP+TLS connection.
enum SmolStream {
/// A plain TCP connection.
Plain(Async<TcpStream>),
Plain(TcpStream),
/// A TCP connection secured by TLS.
Tls(TlsStream<Async<TcpStream>>),
Tls(TlsStream<TcpStream>),
}
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 {
impl AsyncRead for SmolStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
match &mut *self {
SmolStream::Plain(s) => Pin::new(s).poll_read(cx, buf),
SmolStream::Tls(s) => Pin::new(s).poll_read(cx, buf),
SmolStream::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
SmolStream::Tls(stream) => Pin::new(stream).poll_read(cx, buf),
}
}
}
impl tokio::io::AsyncWrite for SmolStream {
impl AsyncWrite for SmolStream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match &mut *self {
SmolStream::Plain(s) => Pin::new(s).poll_write(cx, buf),
SmolStream::Tls(s) => Pin::new(s).poll_write(cx, buf),
SmolStream::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
SmolStream::Tls(stream) => Pin::new(stream).poll_write(cx, buf),
}
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
SmolStream::Plain(stream) => Pin::new(stream).poll_close(cx),
SmolStream::Tls(stream) => Pin::new(stream).poll_close(cx),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
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<io::Result<()>> {
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::Plain(stream) => Pin::new(stream).poll_flush(cx),
SmolStream::Tls(stream) => Pin::new(stream).poll_flush(cx),
}
}
}

View File

@ -13,24 +13,54 @@
//!
//! Refer to `README.md` to see how to the TLS certificate was generated.
use std::net::{Shutdown, TcpListener, TcpStream};
use std::net::{TcpListener, TcpStream};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use anyhow::{Error, Result};
use anyhow::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};
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::service::service_fn;
use hyper::{Request, Response};
use macro_rules_attribute::apply;
use smol::{future, io, prelude::*, Async, Executor};
use smol_hyper::rt::{FuturesIo, SmolTimer};
use smol_macros::main;
/// Serves a request and returns a response.
async fn serve(req: Request<Body>, host: String) -> Result<Response<Body>> {
println!("Serving {}{}", host, req.uri());
Ok(Response::new(Body::from("Hello from hyper!")))
async fn serve(req: Request<Incoming>) -> Result<Response<Full<&'static [u8]>>> {
println!("Serving {}", req.uri());
Ok(Response::new(Full::new("Hello from hyper!".as_bytes())))
}
/// Handle a new client.
async fn handle_client(client: Async<TcpStream>, tls: Option<TlsAcceptor>) -> Result<()> {
// Wrap it in TLS if necessary.
let client = match &tls {
None => SmolStream::Plain(client),
Some(tls) => {
// In case of HTTPS, establish a secure TLS connection.
SmolStream::Tls(tls.accept(client).await?)
}
};
// Build the server.
hyper::server::conn::http1::Builder::new()
.timer(SmolTimer::new())
.serve_connection(FuturesIo::new(client), service_fn(serve))
.await?;
Ok(())
}
/// Listens for incoming connections and serves them.
async fn listen(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Result<()> {
async fn listen(
ex: &Arc<Executor<'static>>,
listener: Async<TcpListener>,
tls: Option<TlsAcceptor>,
) -> Result<()> {
// Format the full host address.
let host = &match tls {
None => format!("http://{}", listener.get_ref().local_addr()?),
@ -38,85 +68,42 @@ async fn listen(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Resul
};
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?;
loop {
// Wait for a new client.
let (client, _) = listener.accept().await?;
Ok(())
// Spawn a task to handle this connection.
ex.spawn({
let tls = tls.clone();
async move {
if let Err(e) = handle_client(client, tls).await {
println!("Error while handling client: {}", e);
}
}
})
.detach();
}
}
fn main() -> Result<()> {
#[apply(main!)]
async fn main(ex: &Arc<Executor<'static>>) -> 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::<TcpListener>::bind(([127, 0, 0, 1], 8000))?, None);
let https = listen(
Async::<TcpListener>::bind(([127, 0, 0, 1], 8001))?,
Some(tls),
);
future::try_zip(http, https).await?;
Ok(())
})
}
/// Spawns futures.
#[derive(Clone)]
struct SmolExecutor;
impl<F: Future + Send + 'static> hyper::rt::Executor<F> for SmolExecutor {
fn execute(&self, fut: F) {
smol::spawn(async { drop(fut.await) }).detach();
}
}
/// Listens for incoming connections.
struct SmolListener {
listener: Async<TcpListener>,
tls: Option<TlsAcceptor>,
}
impl SmolListener {
fn new(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Self {
Self { listener, tls }
}
}
impl hyper::server::accept::Accept for SmolListener {
type Conn = SmolStream;
type Error = Error;
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
let incoming = self.listener.incoming();
smol::pin!(incoming);
let stream = smol::ready!(incoming.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)))
}
let http = listen(
ex,
Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?,
None,
);
let https = listen(
ex,
Async::<TcpListener>::bind(([127, 0, 0, 1], 8001))?,
Some(tls),
);
future::try_zip(http, https).await?;
Ok(())
}
/// A TCP or TCP+TLS connection.
@ -126,70 +113,44 @@ enum SmolStream {
/// A TCP connection secured by TLS.
Tls(TlsStream<Async<TcpStream>>),
/// A TCP connection that is in process of getting secured by TLS.
Handshake(Pin<Box<dyn Future<Output = io::Result<TlsStream<Async<TcpStream>>>> + 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 {
impl AsyncRead for SmolStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
loop {
match &mut *self {
SmolStream::Plain(s) => return Pin::new(s).poll_read(cx, buf),
SmolStream::Tls(s) => return Pin::new(s).poll_read(cx, buf),
SmolStream::Handshake(f) => {
let s = smol::ready!(f.as_mut().poll(cx))?;
*self = SmolStream::Tls(s);
}
}
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_read(cx, buf),
Self::Tls(s) => Pin::new(s).poll_read(cx, buf),
}
}
}
impl tokio::io::AsyncWrite for SmolStream {
impl AsyncWrite for SmolStream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
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);
}
}
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_write(cx, buf),
Self::Tls(s) => Pin::new(s).poll_write(cx, buf),
}
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_close(cx),
Self::Tls(s) => Pin::new(s).poll_close(cx),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
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<io::Result<()>> {
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(())),
Self::Plain(s) => Pin::new(s).poll_close(cx),
Self::Tls(s) => Pin::new(s).poll_close(cx),
}
}
}

View File

@ -9,6 +9,7 @@
#[cfg(target_os = "linux")]
fn main() -> std::io::Result<()> {
use std::ffi::OsString;
use std::os::unix::io::AsFd;
use inotify::{EventMask, Inotify, WatchMask};
use smol::{io, Async};
@ -34,15 +35,16 @@ fn main() -> std::io::Result<()> {
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)?;
let mut inotify = Inotify::init()?;
let source = Async::new(inotify.as_fd().try_clone_to_owned()?)?;
inotify.watches().add(".", 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? {
for event in source.read_with(|_| read_op(&mut inotify)).await? {
println!("{:?}", event);
}
}

View File

@ -8,20 +8,11 @@
#[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};
/// Converts a [`nix::Error`] into [`std::io::Error`].
fn io_err(err: nix::Error) -> io::Error {
match err {
nix::Error::Sys(code) => code.into(),
err => io::Error::new(io::ErrorKind::Other, Box::new(err)),
}
}
/// Sleeps using an OS timer.
async fn sleep(dur: Duration) -> io::Result<()> {
// Create an OS timer.
@ -30,7 +21,7 @@ fn main() -> std::io::Result<()> {
// 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_err))
.read_with(|t| rustix::io::read(t, &mut [0u8; 8]).map_err(io::Error::from))
.await?;
Ok(())
}

View File

@ -8,14 +8,15 @@
#[cfg(unix)]
fn main() -> std::io::Result<()> {
use std::os::unix::net::UnixStream;
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::<UnixStream>::pair()?;
signal_hook::pipe::register(signal_hook::SIGINT, a)?;
// 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.

View File

@ -18,7 +18,7 @@ use std::task::{Context, Poll};
use anyhow::{bail, Context as _, Result};
use async_native_tls::{Certificate, TlsConnector, TlsStream};
use async_tungstenite::WebSocketStream;
use async_tungstenite::{tungstenite, WebSocketStream};
use futures::sink::{Sink, SinkExt};
use smol::{prelude::*, Async};
use tungstenite::handshake::client::Response;

View File

@ -18,7 +18,7 @@ use std::task::{Context, Poll};
use anyhow::{Context as _, Result};
use async_native_tls::{Identity, TlsAcceptor, TlsStream};
use async_tungstenite::WebSocketStream;
use async_tungstenite::{tungstenite, WebSocketStream};
use futures::sink::{Sink, SinkExt};
use smol::{future, prelude::*, Async};
use tungstenite::Message;

View File

@ -8,41 +8,112 @@
#[cfg(windows)]
fn main() -> std::io::Result<()> {
use std::ops::Deref;
use std::os::windows::io::{AsRawSocket, AsSocket, BorrowedSocket};
use std::path::PathBuf;
use smol::{io, prelude::*, Async, Unblock};
use smol::{future, prelude::*, Async, Unblock};
use std::io;
use tempfile::tempdir;
use uds_windows::{UnixListener, UnixStream};
// n.b.: notgull: uds_windows does not support I/O safety yet, hence the wrapper types
struct UnixListener(uds_windows::UnixListener);
impl From<uds_windows::UnixListener> for UnixListener {
fn from(ul: uds_windows::UnixListener) -> Self {
Self(ul)
}
}
impl Deref for UnixListener {
type Target = uds_windows::UnixListener;
fn deref(&self) -> &uds_windows::UnixListener {
&self.0
}
}
impl AsSocket for UnixListener {
fn as_socket(&self) -> BorrowedSocket<'_> {
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
}
}
struct UnixStream(uds_windows::UnixStream);
impl From<uds_windows::UnixStream> for UnixStream {
fn from(ul: uds_windows::UnixStream) -> Self {
Self(ul)
}
}
impl Deref for UnixStream {
type Target = uds_windows::UnixStream;
fn deref(&self) -> &uds_windows::UnixStream {
&self.0
}
}
impl AsSocket for UnixStream {
fn as_socket(&self) -> BorrowedSocket<'_> {
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
}
}
impl io::Read for UnixStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
io::Read::read(&mut self.0, buf)
}
}
impl io::Write for UnixStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
io::Write::write(&mut self.0, buf)
}
fn flush(&mut self) -> io::Result<()> {
io::Write::flush(&mut self.0)
}
}
unsafe impl async_io::IoSafe for UnixStream {}
async fn client(addr: PathBuf) -> io::Result<()> {
// Connect to the address.
let stream = Async::new(UnixStream::connect(addr)?)?;
let stream = Async::new(UnixStream::from(uds_windows::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?;
futures_lite::io::copy(stream, &mut stdout).await?;
Ok(())
}
let dir = tempdir()?;
let path = dir.path().join("socket");
smol::block_on(async {
future::block_on(async {
// Create a listener.
let listener = Async::new(UnixListener::bind(&path)?)?;
let listener = Async::new(UnixListener::from(uds_windows::UnixListener::bind(&path)?))?;
println!("Listening on {:?}", listener.get_ref().local_addr()?);
// Spawn a client task.
let task = smol::spawn(client(path));
future::try_zip(
async {
// Accept the client.
let (stream, _) = listener.read_with(|l| l.accept()).await?;
println!("Accepted a client");
// 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?;
// Send a message, drop the stream, and wait for the client.
Async::new(UnixStream::from(stream))?
.write_all(b"Hello!\n")
.await?;
Ok(())
},
client(path),
)
.await?;
Ok(())
})

View File

@ -1 +0,0 @@
version = 'Two'

View File

@ -28,101 +28,35 @@
//! There's a lot more in the [examples] directory.
//!
//! [`async-compat`]: https://docs.rs/async-compat
//! [examples]: https://github.com/stjepang/smol/tree/master/examples
//! [get-request]: https://github.com/stjepang/smol/blob/master/examples/get-request.rs
//! [examples]: https://github.com/smol-rs/smol/tree/master/examples
//! [get-request]: https://github.com/smol-rs/smol/blob/master/examples/get-request.rs
#![doc(
html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
)]
#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#[cfg(doctest)]
doc_comment::doctest!("../README.md");
use std::future::Future;
use std::panic::catch_unwind;
use std::thread;
use once_cell::sync::Lazy;
#[doc(inline)]
pub use {
async_executor::{Executor, LocalExecutor, Task},
async_io::{block_on, Async, Timer},
blocking::{unblock, Unblock},
futures_lite::{future, io, stream},
futures_lite::{pin, ready},
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,
};
pub use {async_channel as channel, async_fs as fs, async_lock as lock, async_net as net};
pub mod prelude {
//! Traits [`Future`], [`AsyncBufRead`], [`AsyncRead`], [`AsyncSeek`], [`AsyncWrite`], and
//! their extensions.
//!
//! # Examples
//!
//! ```
//! use smol::prelude::*;
//! ```
#[cfg(not(target_os = "espidf"))]
#[doc(inline)]
pub use async_process as process;
#[doc(no_inline)]
pub use futures_lite::{
future::{Future, FutureExt},
io::{AsyncBufRead, AsyncBufReadExt},
io::{AsyncRead, AsyncReadExt},
io::{AsyncSeek, AsyncSeekExt},
io::{AsyncWrite, AsyncWriteExt},
stream::{Stream, StreamExt},
};
}
/// 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<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
static GLOBAL: Lazy<Executor<'_>> = Lazy::new(|| {
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(|| async_io::block_on(GLOBAL.run(future::pending::<()>())))
.ok();
}
})
.expect("cannot spawn executor thread");
}
Executor::new()
});
GLOBAL.spawn(future)
}
mod spawn;
pub use spawn::spawn;

61
src/spawn.rs Normal file
View File

@ -0,0 +1,61 @@
use 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<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
static GLOBAL: OnceCell<Executor<'_>> = 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");
}
// Prevent spawning another thread by running the process driver on this thread.
let ex = Executor::new();
#[cfg(not(target_os = "espidf"))]
ex.spawn(async_process::driver()).detach();
ex
})
}
global().spawn(future)
}