Created
October 30, 2023 23:35
-
-
Save ryanmcgrath/17a4ddd6b7647f181c2aa96b9ae278c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::future::Future; | |
use std::pin::Pin; | |
use std::sync::{Arc, Mutex}; | |
use std::task::{Context, Poll}; | |
// Just placeholders. | |
type CronetPtr = i32; | |
type Error = Box<dyn std::error::Error>; | |
type CronetResult = std::result::Result<(), Error>; | |
#[derive(Debug)] | |
pub enum HTTPMethod { | |
GET, | |
POST, | |
// etc.. | |
} | |
#[derive(Clone, Debug)] | |
pub struct CronetEngine { | |
inner: Arc<Mutex<CronetPtr>>, | |
} | |
impl CronetEngine { | |
pub fn new() -> Self { | |
Self { | |
inner: Arc::new(Mutex::new(0)), | |
} | |
} | |
pub fn request<S>(&self, url: S) -> CronetRequestBuilder | |
where | |
S: Into<String>, | |
{ | |
CronetRequestBuilder::new(self.clone(), url) | |
} | |
pub fn execute(&self, request: CronetRequest) -> impl Future<Output = CronetResult> { | |
// File the request with the engine, setting any necessary ffi hooks for handling | |
// callbacks, set the necessary fields for Future checking on request, then just | |
// return it so the caller can await it | |
request | |
} | |
} | |
#[derive(Debug)] | |
pub struct CronetRequest { | |
pub url: String, | |
pub method: HTTPMethod | |
} | |
impl Future for CronetRequest { | |
type Output = CronetResult; | |
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | |
println!("Checking request status..."); | |
cx.waker().wake_by_ref(); | |
Poll::Pending | |
} | |
} | |
#[derive(Debug)] | |
pub struct CronetRequestBuilder { | |
engine: CronetEngine, | |
inner: CronetRequest | |
} | |
impl CronetRequestBuilder { | |
pub fn new<S>(engine: CronetEngine, url: S) -> Self | |
where | |
S: Into<String>, | |
{ | |
let inner = CronetRequest { | |
url: url.into(), | |
method: HTTPMethod::GET | |
}; | |
Self { | |
engine, | |
inner | |
} | |
} | |
pub fn method(mut self, method: HTTPMethod) -> Self { | |
self.inner.method = method; | |
self | |
} | |
pub fn send(self) -> impl Future<Output = Result<(), Box<dyn std::error::Error>>> { | |
self.engine.execute(self.inner) | |
} | |
} | |
#[tokio::main(flavor = "current_thread")] | |
async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let engine = CronetEngine::new(); | |
let request = engine.request("https://rymc.io/") | |
.method(HTTPMethod::POST) | |
.send().await?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment