]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/wasi/args.rs
Auto merge of #76265 - Dylan-DPC:rollup-j3i509l, r=Dylan-DPC
[rust.git] / library / std / src / sys / wasi / args.rs
1 use crate::ffi::{CStr, OsStr, OsString};
2 use crate::marker::PhantomData;
3 use crate::os::wasi::ffi::OsStrExt;
4 use crate::vec;
5
6 pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
7
8 pub unsafe fn cleanup() {}
9
10 pub struct Args {
11     iter: vec::IntoIter<OsString>,
12     _dont_send_or_sync_me: PhantomData<*mut ()>,
13 }
14
15 /// Returns the command line arguments
16 pub fn args() -> Args {
17     Args {
18         iter: maybe_args().unwrap_or(Vec::new()).into_iter(),
19         _dont_send_or_sync_me: PhantomData,
20     }
21 }
22
23 fn maybe_args() -> Option<Vec<OsString>> {
24     unsafe {
25         let (argc, buf_size) = wasi::args_sizes_get().ok()?;
26         let mut argv = Vec::with_capacity(argc);
27         let mut buf = Vec::with_capacity(buf_size);
28         wasi::args_get(argv.as_mut_ptr(), buf.as_mut_ptr()).ok()?;
29         argv.set_len(argc);
30         let mut ret = Vec::with_capacity(argc);
31         for ptr in argv {
32             let s = CStr::from_ptr(ptr.cast());
33             ret.push(OsStr::from_bytes(s.to_bytes()).to_owned());
34         }
35         Some(ret)
36     }
37 }
38
39 impl Args {
40     pub fn inner_debug(&self) -> &[OsString] {
41         self.iter.as_slice()
42     }
43 }
44
45 impl Iterator for Args {
46     type Item = OsString;
47     fn next(&mut self) -> Option<OsString> {
48         self.iter.next()
49     }
50     fn size_hint(&self) -> (usize, Option<usize>) {
51         self.iter.size_hint()
52     }
53 }
54
55 impl ExactSizeIterator for Args {
56     fn len(&self) -> usize {
57         self.iter.len()
58     }
59 }
60
61 impl DoubleEndedIterator for Args {
62     fn next_back(&mut self) -> Option<OsString> {
63         self.iter.next_back()
64     }
65 }