feat: add async 101 example

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
This commit is contained in:
Vincenzo Palazzo 2023-01-27 17:21:24 +01:00
parent 17119c827a
commit 198b0872af
Signed by: vincenzopalazzo
GPG Key ID: 8B6DC2B870B80D5F
7 changed files with 1336 additions and 15 deletions

1284
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,4 +4,5 @@ members = [
"custom_rio",
"rust_101",
"tutotrial_cli",
"asyc_101",
]

11
asyc_101/Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "asyc_101"
version = "0.1.0"
edition = "2021"
[dependencies]
surf = { version = "2.3.2", features = [ "h1-client" ] }
custom_rio = { path = "../custom_rio" }
log = "0.4"
env_logger = "0.9.1"

44
asyc_101/src/lib.rs Normal file
View File

@ -0,0 +1,44 @@
#![allow(dead_code)]
use log::{debug, info};
use surf;
/// Make an http request to Github API and return the result.
async fn ping_github() -> Result<String, surf::Error> {
debug!("Running the https request");
let mut res = surf::get("https://api.github.com/octocat").await?;
let body = res.body_string().await?;
info!("{}", body);
Ok(body)
}
#[cfg(test)]
mod tests {
use custom_rio::runtime::Runtime;
use custom_rio::CustomRio;
use std::sync::Once;
use crate::ping_github;
static INIT: Once = Once::new();
fn init() {
// ignore error
INIT.call_once(|| {
env_logger::init();
});
}
#[test]
fn safety_test_not_running() {
init();
let _ = ping_github();
}
#[test]
fn safety_test_async_running() {
init();
CustomRio::block_on(async {
let _ = ping_github().await.unwrap();
});
}
}

View File

@ -7,4 +7,4 @@
pub mod runtime;
mod runtime_impl;
pub mod task;
use runtime_impl::CustomRio;
pub use runtime_impl::CustomRio;

View File

@ -5,5 +5,5 @@ use std::future::Future;
pub trait Runtime {
fn new() -> &'static Self;
fn block_on(&self, future: impl Future<Output = ()> + Send + 'static);
fn block_on(future: impl Future<Output = ()> + Send + 'static);
}

View File

@ -3,7 +3,7 @@ use crate::task::Task;
use std::collections::LinkedList;
use std::future::Future;
use std::ops::Deref;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
use std::task::Poll;
@ -82,7 +82,8 @@ impl Runtime for CustomRio {
CustomRio::get()
}
fn block_on(&self, future: impl std::future::Future<Output = ()> + Send + 'static) {
self.spawn_blocking(future);
fn block_on(future: impl std::future::Future<Output = ()> + Send + 'static) {
CustomRio::get().spawn_blocking(future);
while CustomRio::get().size_queue.load(Ordering::Relaxed) > 0 {}
}
}