]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/wasi/args.rs
Rollup merge of #59529 - DevQps:improve-rem-docs, r=cuviper
[rust.git] / src / libstd / sys / wasi / args.rs
1 use crate::any::Any;
2 use crate::ffi::CStr;
3 use crate::ffi::OsString;
4 use crate::marker::PhantomData;
5 use crate::os::wasi::ffi::OsStringExt;
6 use crate::ptr;
7 use crate::vec;
8
9 static mut ARGC: isize = 0;
10 static mut ARGV: *const *const u8 = ptr::null();
11
12 #[cfg(not(target_feature = "atomics"))]
13 pub unsafe fn args_lock() -> impl Any {
14     // No need for a lock if we're single-threaded, but this function will need
15     // to get implemented for multi-threaded scenarios
16 }
17
18 pub unsafe fn init(argc: isize, argv: *const *const u8) {
19     let _guard = args_lock();
20     ARGC = argc;
21     ARGV = argv;
22 }
23
24 pub unsafe fn cleanup() {
25     let _guard = args_lock();
26     ARGC = 0;
27     ARGV = ptr::null();
28 }
29
30 pub struct Args {
31     iter: vec::IntoIter<OsString>,
32     _dont_send_or_sync_me: PhantomData<*mut ()>,
33 }
34
35 /// Returns the command line arguments
36 pub fn args() -> Args {
37     unsafe {
38         let _guard = args_lock();
39         let args = (0..ARGC)
40             .map(|i| {
41                 let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char);
42                 OsStringExt::from_vec(cstr.to_bytes().to_vec())
43             })
44             .collect::<Vec<_>>();
45         Args {
46             iter: args.into_iter(),
47             _dont_send_or_sync_me: PhantomData,
48         }
49     }
50 }
51
52 impl Args {
53     pub fn inner_debug(&self) -> &[OsString] {
54         self.iter.as_slice()
55     }
56 }
57
58 impl Iterator for Args {
59     type Item = OsString;
60     fn next(&mut self) -> Option<OsString> {
61         self.iter.next()
62     }
63     fn size_hint(&self) -> (usize, Option<usize>) {
64         self.iter.size_hint()
65     }
66 }
67
68 impl ExactSizeIterator for Args {
69     fn len(&self) -> usize {
70         self.iter.len()
71     }
72 }
73
74 impl DoubleEndedIterator for Args {
75     fn next_back(&mut self) -> Option<OsString> {
76         self.iter.next_back()
77     }
78 }