]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/sgx/args.rs
8fb35d7ef98bd30974b43341488ecdcf4c72853a
[rust.git] / src / libstd / sys / sgx / args.rs
1 // Copyright 2018 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 use ffi::OsString;
12 use super::abi::usercalls::{copy_user_buffer, alloc, ByteBuffer};
13 use sync::atomic::{AtomicUsize, Ordering};
14 use sys::os_str::Buf;
15 use sys_common::FromInner;
16 use slice;
17
18 static ARGS: AtomicUsize = AtomicUsize::new(0);
19 type ArgsStore = Vec<OsString>;
20
21 pub unsafe fn init(argc: isize, argv: *const *const u8) {
22     if argc != 0 {
23         let args = alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _);
24         let args = args.iter()
25             .map( |a| OsString::from_inner(Buf { inner: copy_user_buffer(a) }) )
26             .collect::<ArgsStore>();
27         ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed);
28     }
29 }
30
31 pub unsafe fn cleanup() {
32     let args = ARGS.swap(0, Ordering::Relaxed);
33     if args != 0 {
34         drop(Box::<ArgsStore>::from_raw(args as _))
35     }
36 }
37
38 pub fn args() -> Args {
39     let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
40     if let Some(args) = args {
41         Args(args.iter())
42     } else {
43         Args([].iter())
44     }
45 }
46
47 pub struct Args(slice::Iter<'static, OsString>);
48
49 impl Args {
50     pub fn inner_debug(&self) -> &[OsString] {
51         self.0.as_slice()
52     }
53 }
54
55 impl Iterator for Args {
56     type Item = OsString;
57     fn next(&mut self) -> Option<OsString> {
58         self.0.next().cloned()
59     }
60     fn size_hint(&self) -> (usize, Option<usize>) {
61         self.0.size_hint()
62     }
63 }
64
65 impl ExactSizeIterator for Args {
66     fn len(&self) -> usize {
67         self.0.len()
68     }
69 }
70
71 impl DoubleEndedIterator for Args {
72     fn next_back(&mut self) -> Option<OsString> {
73         self.0.next_back().cloned()
74     }
75 }