1 // Copyright 2012-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.
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.
11 //! Global storage for command line arguments
13 //! The current incarnation of the Rust runtime expects for
14 //! the processes `argc` and `argv` arguments to be stored
15 //! in a globally-accessible location for use by the `os` module.
17 //! XXX: Would be nice for this to not exist.
18 //! XXX: This has a lot of C glue for lack of globals.
21 use option::{Option, Some, None};
24 use unstable::finally::Finally;
27 /// One-time global initialization.
28 pub unsafe fn init(argc: int, argv: **u8) {
29 let args = load_argc_and_argv(argc, argv);
33 /// One-time global cleanup.
35 rtassert!(take().is_some());
38 /// Take the global arguments from global storage.
39 pub fn take() -> Option<~[~str]> {
41 let ptr = get_global_ptr();
42 let val = util::replace(&mut *ptr, None);
43 val.map(|s: &~~[~str]| (**s).clone())
47 /// Give the global arguments to global storage.
49 /// It is an error if the arguments already exist.
50 pub fn put(args: ~[~str]) {
52 let ptr = get_global_ptr();
53 rtassert!((*ptr).is_none());
54 (*ptr) = Some(~args.clone());
58 /// Make a clone of the global arguments.
59 pub fn clone() -> Option<~[~str]> {
61 let ptr = get_global_ptr();
62 (*ptr).map(|s: &~~[~str]| (**s).clone())
66 fn with_lock<T>(f: &fn() -> T) -> T {
69 rust_take_global_args_lock();
74 rust_drop_global_args_lock();
79 fn get_global_ptr() -> *mut Option<~~[~str]> {
80 unsafe { rust_get_global_args_ptr() }
84 unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~str] {
86 for uint::range(0, argc as uint) |i| {
87 args.push(str::raw::from_c_str(*(argv as **libc::c_char).offset(i)));
93 fn rust_take_global_args_lock();
94 fn rust_drop_global_args_lock();
95 fn rust_get_global_args_ptr() -> *mut Option<~~[~str]>;
100 use option::{Some, None};
102 use unstable::finally::Finally;
106 // Preserve the actual global state.
107 let saved_value = take();
109 let expected = ~[~"happy", ~"today?"];
111 put(expected.clone());
112 assert!(clone() == Some(expected.clone()));
113 assert!(take() == Some(expected.clone()));
114 assert!(take() == None);
118 // Restore the actual global state.
120 Some(ref args) => put(args.clone()),