1
0

eval.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #![doc = include_str!("../docs/eval.md")]
  2. use crate::error::EvalError;
  3. use generational_box::GenerationalBox;
  4. use std::future::{poll_fn, Future, IntoFuture};
  5. use std::pin::Pin;
  6. use std::task::{Context, Poll};
  7. #[doc = include_str!("../docs/eval.md")]
  8. pub struct Eval {
  9. evaluator: GenerationalBox<Box<dyn Evaluator>>,
  10. }
  11. impl Eval {
  12. /// Create this eval from a dynamic evaluator
  13. pub fn new(evaluator: GenerationalBox<Box<dyn Evaluator + 'static>>) -> Self {
  14. Self { evaluator }
  15. }
  16. /// Wait until the javascript task is finished and return the result
  17. pub async fn join<T: serde::de::DeserializeOwned>(self) -> Result<T, EvalError> {
  18. let json_value = poll_fn(|cx| match self.evaluator.try_write() {
  19. Ok(mut evaluator) => evaluator.poll_join(cx),
  20. Err(_) => Poll::Ready(Err(EvalError::Finished)),
  21. })
  22. .await?;
  23. serde_json::from_value(json_value).map_err(EvalError::Serialization)
  24. }
  25. /// Send a message to the javascript task
  26. pub fn send(&self, data: impl serde::Serialize) -> Result<(), EvalError> {
  27. match self.evaluator.try_read() {
  28. Ok(evaluator) => {
  29. evaluator.send(serde_json::to_value(data).map_err(EvalError::Serialization)?)
  30. }
  31. Err(_) => Err(EvalError::Finished),
  32. }
  33. }
  34. /// Receive a message from the javascript task
  35. pub async fn recv<T: serde::de::DeserializeOwned>(&mut self) -> Result<T, EvalError> {
  36. let json_value = poll_fn(|cx| match self.evaluator.try_write() {
  37. Ok(mut evaluator) => evaluator.poll_recv(cx),
  38. Err(_) => Poll::Ready(Err(EvalError::Finished)),
  39. })
  40. .await?;
  41. serde_json::from_value(json_value).map_err(EvalError::Serialization)
  42. }
  43. }
  44. impl IntoFuture for Eval {
  45. type Output = Result<serde_json::Value, EvalError>;
  46. type IntoFuture = Pin<Box<dyn Future<Output = Self::Output>>>;
  47. fn into_future(self) -> Self::IntoFuture {
  48. Box::pin(self.join().into_future())
  49. }
  50. }
  51. /// The platform's evaluator.
  52. pub trait Evaluator {
  53. /// Sends a message to the evaluated JavaScript.
  54. fn send(&self, data: serde_json::Value) -> Result<(), EvalError>;
  55. /// Receive any queued messages from the evaluated JavaScript.
  56. fn poll_recv(
  57. &mut self,
  58. context: &mut Context<'_>,
  59. ) -> Poll<Result<serde_json::Value, EvalError>>;
  60. /// Gets the return value of the JavaScript
  61. fn poll_join(
  62. &mut self,
  63. context: &mut Context<'_>,
  64. ) -> Poll<Result<serde_json::Value, EvalError>>;
  65. }