librespot/core/src/component.rs

64 lines
1.9 KiB
Rust
Raw Normal View History

2017-01-18 20:39:46 +00:00
macro_rules! component {
($name:ident : $inner:ident { $($key:ident : $ty:ty = $value:expr,)* }) => {
#[derive(Clone)]
pub struct $name(::std::sync::Arc<($crate::session::SessionWeak, ::std::sync::Mutex<$inner>)>);
impl $name {
#[allow(dead_code)]
2018-02-13 07:18:49 +00:00
pub(crate) fn new(session: $crate::session::SessionWeak) -> $name {
debug!(target:"librespot::component", "new {}", stringify!($name));
2017-01-18 20:39:46 +00:00
$name(::std::sync::Arc::new((session, ::std::sync::Mutex::new($inner {
$($key : $value,)*
}))))
}
#[allow(dead_code)]
fn lock<F: FnOnce(&mut $inner) -> R, R>(&self, f: F) -> R {
let mut inner = (self.0).1.lock().expect("Mutex poisoned");
f(&mut inner)
}
#[allow(dead_code)]
fn session(&self) -> $crate::session::Session {
(self.0).0.upgrade()
}
}
struct $inner {
$($key : $ty,)*
}
impl Drop for $inner {
fn drop(&mut self) {
debug!(target:"librespot::component", "drop {}", stringify!($name));
}
}
2017-01-18 20:39:46 +00:00
}
}
2017-01-19 22:45:24 +00:00
use std::cell::UnsafeCell;
2018-02-11 11:37:08 +00:00
use std::sync::Mutex;
2017-01-19 22:45:24 +00:00
2018-02-12 19:20:43 +00:00
pub(crate) struct Lazy<T>(Mutex<bool>, UnsafeCell<Option<T>>);
2018-02-11 11:37:08 +00:00
unsafe impl<T: Sync> Sync for Lazy<T> {}
unsafe impl<T: Send> Send for Lazy<T> {}
2017-01-19 22:45:24 +00:00
2017-01-29 16:25:09 +00:00
#[cfg_attr(feature = "cargo-clippy", allow(mutex_atomic))]
2018-02-11 11:37:08 +00:00
impl<T> Lazy<T> {
2018-02-12 19:20:43 +00:00
pub(crate) fn new() -> Lazy<T> {
2017-01-19 22:45:24 +00:00
Lazy(Mutex::new(false), UnsafeCell::new(None))
}
2018-02-12 19:20:43 +00:00
pub(crate) fn get<F: FnOnce() -> T>(&self, f: F) -> &T {
2017-01-19 22:45:24 +00:00
let mut inner = self.0.lock().unwrap();
if !*inner {
unsafe {
*self.1.get() = Some(f());
}
*inner = true;
}
unsafe { &*self.1.get() }.as_ref().unwrap()
}
}