]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/at_exit_imp.rs
Incorporate a stray test
[rust.git] / src / libstd / sys_common / at_exit_imp.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of running at_exit routines
12 //!
13 //! Documentation can be found on the `rt::at_exit` function.
14
15 use boxed::FnBox;
16 use ptr;
17 use mem;
18 use sys_common::mutex::Mutex;
19
20 type Queue = Vec<Box<FnBox()>>;
21
22 // NB these are specifically not types from `std::sync` as they currently rely
23 // on poisoning and this module needs to operate at a lower level than requiring
24 // the thread infrastructure to be in place (useful on the borders of
25 // initialization/destruction).
26 static LOCK: Mutex = Mutex::new();
27 static mut QUEUE: *mut Queue = ptr::null_mut();
28
29 const DONE: *mut Queue = 1_usize as *mut _;
30
31 // The maximum number of times the cleanup routines will be run. While running
32 // the at_exit closures new ones may be registered, and this count is the number
33 // of times the new closures will be allowed to register successfully. After
34 // this number of iterations all new registrations will return `false`.
35 const ITERS: usize = 10;
36
37 unsafe fn init() -> bool {
38     if QUEUE.is_null() {
39         let state: Box<Queue> = box Vec::new();
40         QUEUE = Box::into_raw(state);
41     } else if QUEUE == DONE {
42         // can't re-init after a cleanup
43         return false
44     }
45
46     true
47 }
48
49 pub fn cleanup() {
50     for i in 1..=ITERS {
51         unsafe {
52             let queue = {
53                 let _guard = LOCK.lock();
54                 mem::replace(&mut QUEUE, if i == ITERS { DONE } else { ptr::null_mut() })
55             };
56
57             // make sure we're not recursively cleaning up
58             assert!(queue != DONE);
59
60             // If we never called init, not need to cleanup!
61             if !queue.is_null() {
62                 let queue: Box<Queue> = Box::from_raw(queue);
63                 for to_run in *queue {
64                     to_run();
65                 }
66             }
67         }
68     }
69 }
70
71 pub fn push(f: Box<FnBox()>) -> bool {
72     unsafe {
73         let _guard = LOCK.lock();
74         if init() {
75             (*QUEUE).push(f);
76             true
77         } else {
78             false
79         }
80     }
81 }