2015-02-24 23:27:20 -08:00
|
|
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
use prelude::v1::*;
|
|
|
|
|
2015-05-27 11:18:36 +03:00
|
|
|
use cell::Cell;
|
2015-09-03 09:49:50 +03:00
|
|
|
use ptr;
|
2015-02-24 23:27:20 -08:00
|
|
|
use sync::{StaticMutex, Arc};
|
2015-09-08 15:53:46 -07:00
|
|
|
use sys_common;
|
2015-02-24 23:27:20 -08:00
|
|
|
|
|
|
|
pub struct Lazy<T> {
|
2015-05-27 11:18:36 +03:00
|
|
|
lock: StaticMutex,
|
|
|
|
ptr: Cell<*mut Arc<T>>,
|
|
|
|
init: fn() -> Arc<T>,
|
2015-02-24 23:27:20 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
unsafe impl<T> Sync for Lazy<T> {}
|
|
|
|
|
|
|
|
impl<T: Send + Sync + 'static> Lazy<T> {
|
2015-05-27 11:18:36 +03:00
|
|
|
pub const fn new(init: fn() -> Arc<T>) -> Lazy<T> {
|
|
|
|
Lazy {
|
|
|
|
lock: StaticMutex::new(),
|
2015-09-03 09:49:50 +03:00
|
|
|
ptr: Cell::new(ptr::null_mut()),
|
2015-05-27 11:18:36 +03:00
|
|
|
init: init
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-24 23:27:20 -08:00
|
|
|
pub fn get(&'static self) -> Option<Arc<T>> {
|
|
|
|
let _g = self.lock.lock();
|
2015-05-27 11:18:36 +03:00
|
|
|
let ptr = self.ptr.get();
|
2015-02-24 23:27:20 -08:00
|
|
|
unsafe {
|
|
|
|
if ptr.is_null() {
|
2015-03-21 11:08:15 -07:00
|
|
|
Some(self.init())
|
2015-02-24 23:27:20 -08:00
|
|
|
} else if ptr as usize == 1 {
|
2015-03-21 11:08:15 -07:00
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some((*ptr).clone())
|
2015-02-24 23:27:20 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-21 11:08:15 -07:00
|
|
|
unsafe fn init(&'static self) -> Arc<T> {
|
|
|
|
// If we successfully register an at exit handler, then we cache the
|
|
|
|
// `Arc` allocation in our own internal box (it will get deallocated by
|
|
|
|
// the at exit handler). Otherwise we just return the freshly allocated
|
|
|
|
// `Arc`.
|
2015-09-08 15:53:46 -07:00
|
|
|
let registered = sys_common::at_exit(move || {
|
2015-02-24 23:27:20 -08:00
|
|
|
let g = self.lock.lock();
|
2015-05-27 11:18:36 +03:00
|
|
|
let ptr = self.ptr.get();
|
|
|
|
self.ptr.set(1 as *mut _);
|
2015-02-24 23:27:20 -08:00
|
|
|
drop(g);
|
|
|
|
drop(Box::from_raw(ptr))
|
|
|
|
});
|
2015-03-21 11:08:15 -07:00
|
|
|
let ret = (self.init)();
|
|
|
|
if registered.is_ok() {
|
2015-06-10 19:33:04 -07:00
|
|
|
self.ptr.set(Box::into_raw(Box::new(ret.clone())));
|
2015-03-21 11:08:15 -07:00
|
|
|
}
|
2015-09-08 00:36:29 +02:00
|
|
|
ret
|
2015-02-24 23:27:20 -08:00
|
|
|
}
|
|
|
|
}
|