1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use core::sync::atomic::{Ordering, AtomicU8};
use core::mem::MaybeUninit;
use core::ptr;

use std::io;

use tokio::runtime;

//Not set yet
const UNINITIALIZED: u8 = 0;
//Being set
const INITIALIZING: u8 = 1;
//Set
const INITIALIZED: u8 = 2;

static GLOBAL_GUARD: AtomicU8 = AtomicU8::new(UNINITIALIZED);
static mut TOKIO: MaybeUninit<runtime::Runtime> = MaybeUninit::uninit();

const RUNTIME_NOT_AVAIL: &str = "Runtime is not set";
const RUNTIME_TWICE: &str = "Settings runtime twice";
const RUNTIME_RUN: &str = "Runtime is already running";

mod runner {
    pub static MUTEX: crate::guard::WakerVar = crate::guard::WakerVar::new();
}

///Tokio runtime guard
///
///Runtime gets terminated as soon as guard goes out of scope
pub struct Runtime {
}

impl Default for Runtime {
    #[inline]
    fn default() -> Self {
        Self::from_rt(tokio::runtime::Runtime::new().unwrap())
    }
}

impl Runtime {
    ///Initializes runtime from existing tokio's Runtime.
    pub fn from_rt(runtime: runtime::Runtime) -> Self {
        match GLOBAL_GUARD.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::Release) {
            UNINITIALIZED => unsafe {
                ptr::write(TOKIO.as_mut_ptr(), runtime);
                GLOBAL_GUARD.store(INITIALIZED, Ordering::SeqCst);
            },
            _ => panic!(RUNTIME_TWICE),
        }

        Self {
        }
    }

    #[inline]
    ///Creates new instance from provided builder
    ///
    ///This function must be called prior to any usage of runtime related functionality
    ///
    ///## Panics
    ///
    ///If runtime is already initialized.
    pub fn init(builder: &mut runtime::Builder) -> io::Result<Self> {
        let runtime = builder.build()?;
        Ok(Self::from_rt(runtime))
    }

    ///Spins Runtime
    ///
    ///Once called, can be called again only after `stop`.
    ///
    ///Blocks current thread, until `stop` is called.
    pub fn run() {
        if runner::MUTEX.is_armed() {
            panic!(RUNTIME_RUN);
        }

        match GLOBAL_GUARD.load(Ordering::Acquire) {
            INITIALIZED => unsafe {
                let tokio = &mut *TOKIO.as_mut_ptr();
                tokio.block_on(runner::MUTEX.lock());
            },
            _ => panic!(RUNTIME_NOT_AVAIL)
        }
    }

    ///Signals Runtime to terminate
    pub fn stop() {
        runner::MUTEX.wake();
    }
}

fn with_runtime<R, FN: FnOnce(&runtime::Runtime) -> R>(cb: FN) -> R {
    match GLOBAL_GUARD.load(Ordering::Acquire) {
        INITIALIZED => unsafe {
            cb(&*TOKIO.as_ptr())
        },
        _ => panic!(RUNTIME_NOT_AVAIL)
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        match GLOBAL_GUARD.compare_and_swap(INITIALIZED, INITIALIZING, Ordering::Release) {
            INITIALIZED => unsafe {
                ptr::drop_in_place(TOKIO.as_mut_ptr());
                GLOBAL_GUARD.store(UNINITIALIZED, Ordering::SeqCst);
            },
            _ => panic!("Runtime is not set, but dropping global guard!"),
        }
    }
}

struct Ptr<T>(*mut T);

impl<T> Ptr<T> {
    #[inline(always)]
    fn write(&self, val: T) {
        unsafe {
            ptr::write(self.0, val)
        }
    }
}

unsafe impl<T> Send for Ptr<T> {}
unsafe impl<T> Sync for Ptr<T> {}

impl<F: core::future::Future> super::AutoRuntime for F {
    fn wait(self) -> Self::Output where Self: Send + core::future::Future + 'static, Self::Output: Send + 'static {
        let mut result = MaybeUninit::uninit();

        let blocking = crate::blocking::Block::new();
        let (signal, lock) = blocking.split();

        let result_ptr = Ptr(result.as_mut_ptr());

        with_runtime(|rt| rt.spawn(async move {
            result_ptr.write(self.await);
            signal.signal();
        }));

        lock.wait();

        unsafe {
            result.assume_init()
        }
    }

    #[inline]
    fn spawn(self) -> tokio::task::JoinHandle<Self::Output> where Self: Send + core::future::Future + 'static, Self::Output: Send + 'static {
        with_runtime(|rt| rt.spawn(self))
    }
}