-
-
Notifications
You must be signed in to change notification settings - Fork 106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(wasm): Add util creates for runtime,future and time primitives for wasm #350
Closed
irvingoujAtDevolution
wants to merge
7
commits into
Eugeny:main
from
irvingoujAtDevolution:support-wasm-utils
Closed
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2cf485c
feat(wasm): Add util creates for runtime,future and time primitives f…
irvingoujAtDevolution 77bea62
Add comments
irvingoujAtDevolution e1e9e8c
Create runtime.rs
irvingoujAtDevolution c9667a6
allow dead code
irvingoujAtDevolution 0d7ad5c
fmt
irvingoujAtDevolution 25c0847
Update time.rs
irvingoujAtDevolution 686cd89
update cargo.toml
irvingoujAtDevolution File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
[package] | ||
name = "russh-util" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] | ||
chrono = "0.4.38" | ||
|
||
[dev-dependencies] | ||
futures-executor = "0.3.13" | ||
static_assertions = "1.1.0" | ||
|
||
|
||
[target.'cfg(target_arch = "wasm32")'.dependencies] | ||
wasm-bindgen = "0.2" | ||
wasm-bindgen-futures = "0.4.43" | ||
|
||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] | ||
tokio = { version = "1.17", features = [ | ||
"io-util", | ||
"macros", | ||
"sync", | ||
"rt-multi-thread", | ||
"rt", | ||
] } |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,158 @@ | ||
/// This file is a copy of the `ReusableBoxFuture` type from the `tokio-util` crate. | ||
use std::alloc::Layout; | ||
use std::fmt; | ||
use std::future::{self, Future}; | ||
use std::mem::{self, ManuallyDrop}; | ||
use std::pin::Pin; | ||
use std::ptr; | ||
use std::task::{Context, Poll}; | ||
|
||
/// A reusable `Pin<Box<dyn Future<Output = T> + Send + 'a>>`. | ||
/// | ||
/// This type lets you replace the future stored in the box without | ||
/// reallocating when the size and alignment permits this. | ||
pub struct ReusableBoxFuture<'a, T> { | ||
boxed: Pin<Box<dyn Future<Output = T> + Send + 'a>>, | ||
} | ||
|
||
impl<'a, T> ReusableBoxFuture<'a, T> { | ||
/// Create a new `ReusableBoxFuture<T>` containing the provided future. | ||
pub fn new<F>(future: F) -> Self | ||
where | ||
F: Future<Output = T> + Send + 'a, | ||
{ | ||
Self { | ||
boxed: Box::pin(future), | ||
} | ||
} | ||
|
||
/// Replace the future currently stored in this box. | ||
/// | ||
/// This reallocates if and only if the layout of the provided future is | ||
/// different from the layout of the currently stored future. | ||
pub fn set<F>(&mut self, future: F) | ||
where | ||
F: Future<Output = T> + Send + 'a, | ||
{ | ||
if let Err(future) = self.try_set(future) { | ||
*self = Self::new(future); | ||
} | ||
} | ||
|
||
/// Replace the future currently stored in this box. | ||
/// | ||
/// This function never reallocates, but returns an error if the provided | ||
/// future has a different size or alignment from the currently stored | ||
/// future. | ||
pub fn try_set<F>(&mut self, future: F) -> Result<(), F> | ||
where | ||
F: Future<Output = T> + Send + 'a, | ||
{ | ||
// If we try to inline the contents of this function, the type checker complains because | ||
// the bound `T: 'a` is not satisfied in the call to `pending()`. But by putting it in an | ||
// inner function that doesn't have `T` as a generic parameter, we implicitly get the bound | ||
// `F::Output: 'a` transitively through `F: 'a`, allowing us to call `pending()`. | ||
#[inline(always)] | ||
fn real_try_set<'a, F>( | ||
this: &mut ReusableBoxFuture<'a, F::Output>, | ||
future: F, | ||
) -> Result<(), F> | ||
where | ||
F: Future + Send + 'a, | ||
{ | ||
// future::Pending<T> is a ZST so this never allocates. | ||
let boxed = mem::replace(&mut this.boxed, Box::pin(future::pending())); | ||
reuse_pin_box(boxed, future, |boxed| this.boxed = Pin::from(boxed)) | ||
} | ||
|
||
real_try_set(self, future) | ||
} | ||
|
||
/// Get a pinned reference to the underlying future. | ||
pub fn get_pin(&mut self) -> Pin<&mut (dyn Future<Output = T> + Send)> { | ||
self.boxed.as_mut() | ||
} | ||
|
||
/// Poll the future stored inside this box. | ||
pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<T> { | ||
self.get_pin().poll(cx) | ||
} | ||
} | ||
|
||
impl<T> Future for ReusableBoxFuture<'_, T> { | ||
type Output = T; | ||
|
||
/// Poll the future stored inside this box. | ||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> { | ||
Pin::into_inner(self).get_pin().poll(cx) | ||
} | ||
} | ||
|
||
// The only method called on self.boxed is poll, which takes &mut self, so this | ||
// struct being Sync does not permit any invalid access to the Future, even if | ||
// the future is not Sync. | ||
unsafe impl<T> Sync for ReusableBoxFuture<'_, T> {} | ||
|
||
impl<T> fmt::Debug for ReusableBoxFuture<'_, T> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.debug_struct("ReusableBoxFuture").finish() | ||
} | ||
} | ||
|
||
fn reuse_pin_box<T: ?Sized, U, O, F>(boxed: Pin<Box<T>>, new_value: U, callback: F) -> Result<O, U> | ||
where | ||
F: FnOnce(Box<U>) -> O, | ||
{ | ||
let layout = Layout::for_value::<T>(&*boxed); | ||
if layout != Layout::new::<U>() { | ||
return Err(new_value); | ||
} | ||
|
||
// SAFETY: We don't ever construct a non-pinned reference to the old `T` from now on, and we | ||
// always drop the `T`. | ||
let raw: *mut T = Box::into_raw(unsafe { Pin::into_inner_unchecked(boxed) }); | ||
|
||
// When dropping the old value panics, we still want to call `callback` — so move the rest of | ||
// the code into a guard type. | ||
let guard = CallOnDrop::new(|| { | ||
let raw: *mut U = raw.cast::<U>(); | ||
unsafe { raw.write(new_value) }; | ||
|
||
// SAFETY: | ||
// - `T` and `U` have the same layout. | ||
// - `raw` comes from a `Box` that uses the same allocator as this one. | ||
// - `raw` points to a valid instance of `U` (we just wrote it in). | ||
let boxed = unsafe { Box::from_raw(raw) }; | ||
|
||
callback(boxed) | ||
}); | ||
|
||
// Drop the old value. | ||
unsafe { ptr::drop_in_place(raw) }; | ||
|
||
// Run the rest of the code. | ||
Ok(guard.call()) | ||
} | ||
|
||
struct CallOnDrop<O, F: FnOnce() -> O> { | ||
f: ManuallyDrop<F>, | ||
} | ||
|
||
impl<O, F: FnOnce() -> O> CallOnDrop<O, F> { | ||
fn new(f: F) -> Self { | ||
let f = ManuallyDrop::new(f); | ||
Self { f } | ||
} | ||
fn call(self) -> O { | ||
let mut this = ManuallyDrop::new(self); | ||
let f = unsafe { ManuallyDrop::take(&mut this.f) }; | ||
f() | ||
} | ||
} | ||
|
||
impl<O, F: FnOnce() -> O> Drop for CallOnDrop<O, F> { | ||
fn drop(&mut self) { | ||
let f = unsafe { ManuallyDrop::take(&mut self.f) }; | ||
f(); | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
#![allow(dead_code)] // To be removed when full wasm support is added. | ||
|
||
pub mod future; | ||
pub mod runtime; | ||
pub mod time; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
use std::future::Future; | ||
|
||
pub fn spawn<F>(future: F) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This needs to be generic over |
||
where | ||
F: Future<Output = ()> + 'static + Send, | ||
{ | ||
#[cfg(target_arch = "wasm32")] | ||
{ | ||
wasm_bindgen_futures::spawn_local(future); | ||
} | ||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
{ | ||
tokio::spawn(future); | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
#[cfg(not(target_arch = "wasm32"))] | ||
pub use std::time::Instant; | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
pub use wasm::Instant; | ||
|
||
mod wasm { | ||
#[derive(Debug, Clone, Copy)] | ||
pub struct Instant { | ||
inner: chrono::DateTime<chrono::Utc>, | ||
} | ||
|
||
impl Instant { | ||
pub fn now() -> Self { | ||
Instant { | ||
inner: chrono::Utc::now(), | ||
} | ||
} | ||
|
||
pub fn duration_since(&self, earlier: Instant) -> std::time::Duration { | ||
(self.inner - earlier.inner) | ||
.to_std() | ||
.expect("Duration is negative") | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where is this going to be used?