Add a borrow() function to SendCell

To allow doing the thread check only once for performance reasons.
This commit is contained in:
Sebastian Dröge 2017-08-04 19:56:13 +03:00
parent 3395203a53
commit 5676aeb3ef

View file

@ -85,7 +85,7 @@ fn create_ui(app: &gtk::Application) {
let app_clone = SendCell::new(app.clone()); let app_clone = SendCell::new(app.clone());
bus.add_watch(move |_, msg| { bus.add_watch(move |_, msg| {
let app = &app_clone; let app = app_clone.borrow();
match msg.view() { match msg.view() {
MessageView::Eos(..) => gtk::main_quit(), MessageView::Eos(..) => gtk::main_quit(),
MessageView::Error(err) => { MessageView::Error(err) => {
@ -95,7 +95,7 @@ fn create_ui(app: &gtk::Application) {
err.get_error(), err.get_error(),
err.get_debug() err.get_debug()
); );
app.get().quit(); app.quit();
} }
_ => (), _ => (),
}; };
@ -127,6 +127,7 @@ fn main() {
// but us having to use them in a closure that requires Send // but us having to use them in a closure that requires Send
use std::thread; use std::thread;
use std::cmp; use std::cmp;
use std::ops;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct SendCell<T> { pub struct SendCell<T> {
@ -154,6 +155,27 @@ impl<T> SendCell<T> {
None None
} }
} }
pub fn borrow(&self) -> Ref<T> {
Ref { data: self.get() }
}
pub fn try_borrow(&self) -> Option<Ref<T>> {
self.try_get().map(|data| Ref { data: data })
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ref<'a, T: 'a> {
data: &'a T,
}
impl<'a, T: 'a> ops::Deref for Ref<'a, T> {
type Target = T;
fn deref(&self) -> &T {
self.data
}
} }
impl<T> From<T> for SendCell<T> { impl<T> From<T> for SendCell<T> {