organized imports, formatted code with cargo fmt

This commit is contained in:
coderswat 2023-08-29 19:19:29 +05:30
parent e063efcdf5
commit 79110a4133
4 changed files with 76 additions and 63 deletions

View File

@ -1,24 +1,19 @@
use php_tokio::{EventLoop, php_async_impl};
use nicelocal_ext_php_rs::prelude::*; use nicelocal_ext_php_rs::prelude::*;
use php_tokio::{php_async_impl, EventLoop};
#[php_class] #[php_class]
struct Client { struct Client {}
}
#[php_async_impl] #[php_async_impl]
impl Client { impl Client {
pub fn init() -> PhpResult<u64>{ pub fn init() -> PhpResult<u64> {
EventLoop::init() EventLoop::init()
} }
pub fn wakeup() -> PhpResult<()> { pub fn wakeup() -> PhpResult<()> {
EventLoop::wakeup() EventLoop::wakeup()
} }
pub async fn get(url: &str) -> anyhow::Result<String> { pub async fn get(url: &str) -> anyhow::Result<String> {
Ok(reqwest::get(url) Ok(reqwest::get(url).await?.text().await?)
.await?
.text()
.await?
)
} }
} }
@ -29,7 +24,5 @@ pub extern "C" fn request_shutdown(_type: i32, _module_number: i32) -> i32 {
#[php_module] #[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module module.request_shutdown_function(request_shutdown)
.request_shutdown_function(request_shutdown)
} }

View File

@ -19,7 +19,6 @@
use nicelocal_ext_php_rs::binary_slice::{BinarySlice, PackSlice}; use nicelocal_ext_php_rs::binary_slice::{BinarySlice, PackSlice};
#[inline(always)] #[inline(always)]
pub unsafe fn borrow_unchecked< pub unsafe fn borrow_unchecked<
'original, 'original,

View File

@ -1,20 +1,17 @@
use std::cell::RefCell;
use std::fs::File;
use std::future::Future;
use std::io::{self, Write};
use std::os::fd::{RawFd, FromRawFd};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::io::Read;
use crate::borrow_unchecked::borrow_unchecked; use crate::borrow_unchecked::borrow_unchecked;
use nicelocal_ext_php_rs::boxed::ZBox;
use nicelocal_ext_php_rs::call_user_func;
use nicelocal_ext_php_rs::prelude::*;
use nicelocal_ext_php_rs::types::ZendHashTable;
use nicelocal_ext_php_rs::zend::Function;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use nicelocal_ext_php_rs::{
boxed::ZBox, call_user_func, prelude::*, types::ZendHashTable, zend::Function,
};
use std::{
cell::RefCell,
fs::File,
future::Future,
io::{self, Read, Write},
os::fd::{AsRawFd, FromRawFd, RawFd},
sync::mpsc::{channel, Receiver, Sender},
};
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use std::os::fd::AsRawFd;
lazy_static! { lazy_static! {
pub static ref RUNTIME: Runtime = Runtime::new().expect("Could not allocate runtime"); pub static ref RUNTIME: Runtime = Runtime::new().expect("Could not allocate runtime");
@ -51,12 +48,12 @@ pub struct EventLoop {
impl EventLoop { impl EventLoop {
pub fn init() -> PhpResult<u64> { pub fn init() -> PhpResult<u64> {
EVENTLOOP.with_borrow_mut(|e| { EVENTLOOP.with_borrow_mut(|e| {
Ok( Ok(match e {
match e {
None => e.insert(Self::new()?), None => e.insert(Self::new()?),
Some(ev) => ev Some(ev) => ev,
}.notify_receiver.as_raw_fd() as u64 }
) .notify_receiver
.as_raw_fd() as u64)
}) })
} }
@ -79,23 +76,29 @@ impl EventLoop {
let (future, get_current_suspension) = EVENTLOOP.with_borrow_mut(move |c| { let (future, get_current_suspension) = EVENTLOOP.with_borrow_mut(move |c| {
let c = c.as_mut().unwrap(); let c = c.as_mut().unwrap();
let idx = c.fibers.len() as u64; let idx = c.fibers.len() as u64;
c.fibers.insert_at_index(idx, call_user_func!(c.get_current_suspension).unwrap()).unwrap(); c.fibers
.insert_at_index(idx, call_user_func!(c.get_current_suspension).unwrap())
.unwrap();
let sender = c.sender.clone(); let sender = c.sender.clone();
let mut notifier = c.notify_sender.try_clone().unwrap(); let mut notifier = c.notify_sender.try_clone().unwrap();
(RUNTIME.spawn(async move { (
RUNTIME.spawn(async move {
let res = future.await; let res = future.await;
sender.send(idx).unwrap(); sender.send(idx).unwrap();
notifier.write_all(&[0]).unwrap(); notifier.write_all(&[0]).unwrap();
res res
}), unsafe { }),
borrow_unchecked(&c.get_current_suspension) unsafe { borrow_unchecked(&c.get_current_suspension) },
}) )
}); });
// We suspend the fiber here, the Rust stack is kept alive until the result is ready. // We suspend the fiber here, the Rust stack is kept alive until the result is ready.
call_user_func!(get_current_suspension).unwrap().try_call_method("suspend", vec![]).unwrap(); call_user_func!(get_current_suspension)
.unwrap()
.try_call_method("suspend", vec![])
.unwrap();
// We've resumed, the `future` is already resolved and is not used by the tokio thread, it's safe to drop it. // We've resumed, the `future` is already resolved and is not used by the tokio thread, it's safe to drop it.
@ -110,7 +113,10 @@ impl EventLoop {
for fiber_id in c.receiver.try_iter() { for fiber_id in c.receiver.try_iter() {
if let Some(fiber) = c.fibers.get_index_mut(fiber_id) { if let Some(fiber) = c.fibers.get_index_mut(fiber_id) {
fiber.object_mut().unwrap().try_call_method("resume", vec![])?; fiber
.object_mut()
.unwrap()
.try_call_method("resume", vec![])?;
c.fibers.remove_index(fiber_id); c.fibers.remove_index(fiber_id);
} }
} }
@ -127,10 +133,22 @@ impl EventLoop {
let (notify_receiver, notify_sender) = let (notify_receiver, notify_sender) =
sys_pipe().map_err(|err| format!("Could not create pipe: {}", err))?; sys_pipe().map_err(|err| format!("Could not create pipe: {}", err))?;
if !call_user_func!(Function::from_function("class_exists"), "\\Revolt\\EventLoop")?.bool().unwrap_or(false) { if !call_user_func!(
Function::from_function("class_exists"),
"\\Revolt\\EventLoop"
)?
.bool()
.unwrap_or(false)
{
return Err(format!("\\Revolt\\EventLoop does not exist!").into()); return Err(format!("\\Revolt\\EventLoop does not exist!").into());
} }
if !call_user_func!(Function::from_function("interface_exists"), "\\Revolt\\EventLoop\\Suspension")?.bool().unwrap_or(false) { if !call_user_func!(
Function::from_function("interface_exists"),
"\\Revolt\\EventLoop\\Suspension"
)?
.bool()
.unwrap_or(false)
{
return Err(format!("\\Revolt\\EventLoop\\Suspension does not exist!").into()); return Err(format!("\\Revolt\\EventLoop\\Suspension does not exist!").into());
} }
@ -141,8 +159,11 @@ impl EventLoop {
notify_sender: unsafe { File::from_raw_fd(notify_sender) }, notify_sender: unsafe { File::from_raw_fd(notify_sender) },
notify_receiver: unsafe { File::from_raw_fd(notify_receiver) }, notify_receiver: unsafe { File::from_raw_fd(notify_receiver) },
dummy: [0; 1], dummy: [0; 1],
get_current_suspension: Function::try_from_method("\\Revolt\\EventLoop", "getSuspension").ok_or("\\Revolt\\EventLoop::getSuspension does not exist")?, get_current_suspension: Function::try_from_method(
"\\Revolt\\EventLoop",
"getSuspension",
)
.ok_or("\\Revolt\\EventLoop::getSuspension does not exist")?,
}) })
} }
} }

View File

@ -1,6 +1,6 @@
pub mod borrow_unchecked; pub mod borrow_unchecked;
mod event_loop; mod event_loop;
pub use php_tokio_derive::php_async_impl;
pub use event_loop::RUNTIME;
pub use event_loop::EventLoop; pub use event_loop::EventLoop;
pub use event_loop::RUNTIME;
pub use php_tokio_derive::php_async_impl;