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