#[cfg(not(feature = "std"))]
extern crate alloc;
use aimdb_executor::Runtime;
use core::future::Future;
#[derive(Clone)]
pub struct RuntimeContext<R>
where
R: Runtime,
{
#[cfg(feature = "std")]
runtime: std::sync::Arc<R>,
#[cfg(not(feature = "std"))]
runtime: &'static R,
}
#[cfg(feature = "std")]
impl<R> RuntimeContext<R>
where
R: Runtime,
{
pub fn new(runtime: R) -> Self {
Self {
runtime: std::sync::Arc::new(runtime),
}
}
pub fn from_arc(runtime: std::sync::Arc<R>) -> Self {
Self { runtime }
}
pub fn extract_from_any(ctx_any: std::sync::Arc<dyn core::any::Any + Send + Sync>) -> Self {
let runtime = ctx_any
.downcast::<R>()
.expect("Runtime type mismatch - expected matching runtime adapter");
Self::from_arc(runtime.clone())
}
}
#[cfg(not(feature = "std"))]
impl<R> RuntimeContext<R>
where
R: Runtime,
{
pub fn new(runtime: &'static R) -> Self {
Self { runtime }
}
pub fn extract_from_any(ctx_any: alloc::sync::Arc<dyn core::any::Any + Send + Sync>) -> Self {
let runtime = ctx_any
.downcast::<R>()
.expect("Runtime type mismatch - expected matching runtime adapter");
let runtime_ref: &'static R = &*alloc::boxed::Box::leak(runtime.into());
Self::new(runtime_ref)
}
}
impl<R> RuntimeContext<R>
where
R: Runtime,
{
pub fn time(&self) -> Time<'_, R> {
Time { ctx: self }
}
pub fn log(&self) -> Log<'_, R> {
Log { ctx: self }
}
#[cfg(feature = "std")]
pub fn runtime(&self) -> &R {
&self.runtime
}
#[cfg(not(feature = "std"))]
pub fn runtime(&self) -> &'static R {
self.runtime
}
}
#[cfg(feature = "std")]
impl<R> RuntimeContext<R>
where
R: Runtime,
{
pub fn from_runtime(runtime: R) -> Self {
Self::new(runtime)
}
}
#[cfg(feature = "std")]
pub fn create_runtime_context<R>(runtime: R) -> RuntimeContext<R>
where
R: Runtime,
{
RuntimeContext::from_runtime(runtime)
}
pub struct Time<'a, R: Runtime> {
ctx: &'a RuntimeContext<R>,
}
impl<'a, R: Runtime> Time<'a, R> {
pub fn millis(&self, millis: u64) -> R::Duration {
self.ctx.runtime.millis(millis)
}
pub fn secs(&self, secs: u64) -> R::Duration {
self.ctx.runtime.secs(secs)
}
pub fn micros(&self, micros: u64) -> R::Duration {
self.ctx.runtime.micros(micros)
}
pub fn sleep(&self, duration: R::Duration) -> impl Future<Output = ()> + Send + '_ {
self.ctx.runtime.sleep(duration)
}
pub fn now(&self) -> R::Instant {
self.ctx.runtime.now()
}
pub fn duration_since(&self, later: R::Instant, earlier: R::Instant) -> Option<R::Duration> {
self.ctx.runtime.duration_since(later, earlier)
}
}
pub struct Log<'a, R: Runtime> {
ctx: &'a RuntimeContext<R>,
}
impl<'a, R: Runtime> Log<'a, R> {
pub fn info(&self, message: &str) {
self.ctx.runtime.info(message)
}
pub fn debug(&self, message: &str) {
self.ctx.runtime.debug(message)
}
pub fn warn(&self, message: &str) {
self.ctx.runtime.warn(message)
}
pub fn error(&self, message: &str) {
self.ctx.runtime.error(message)
}
}