Debian Codegraph @

src/argparse/utils.rs

raw
1 use std::{
2 fs,
3 io,
4 };
5
6 use anyhow::{Context, Result};
7
8 /// Returns the file descriptor if the given name is a special
9 /// filename.
10 pub fn special_filename_fd(name: &str) -> Option<i64> {
11 if name.starts_with("-&") {
12 name[2..].parse().ok()
13 } else {
14 None
15 }
16 }
17
18 /// Creates an io::Write from the given file descriptor.
19 pub fn sink_from_fd(fd: i64) -> Result<Box<dyn io::Write + Send + Sync>> {
20 file_sink_from_fd(fd).map(|f| -> Box<dyn io::Write + Send + Sync> {
21 Box::new(f)
22 })
23 }
24
25 /// Creates a fs::File from the given file descriptor.
26 pub fn file_sink_from_fd(fd: i64) -> Result<fs::File> {
27 platform! {
28 unix => {
29 use std::os::unix::io::FromRawFd;
30 let fd = fd.try_into().context(
31 format!("Not a valid file descriptor: {}", fd))?;
32 check_fd(fd)?;
33 Ok(unsafe {
34 fs::File::from_raw_fd(fd)
35 })
36 },
37 windows => {
38 unimplemented!()
39 },
40 }
41 }
42
43 /// Creates an io::Read from the given file descriptor.
44 pub fn source_from_fd(fd: i64) -> Result<fs::File> {
45 platform! {
46 unix => {
47 use std::os::unix::io::FromRawFd;
48 let fd = fd.try_into().context(
49 format!("Not a valid file descriptor: {}", fd))?;
50 check_fd(fd)?;
51 Ok(unsafe {
52 fs::File::from_raw_fd(fd)
53 })
54 },
55 windows => {
56 unimplemented!()
57 },
58 }
59 }
60
61 /// Checks whether the given descriptor is valid.
62 fn check_fd(fd: std::os::fd::RawFd) -> Result<()> {
63 unsafe {
64 // Try to dup(2) it.
65 let dup = libc::dup(fd);
66
67 if dup > 0 {
68 libc::close(dup);
69 Ok(())
70 } else {
71 Err(std::io::Error::last_os_error().into())
72 }
73 }
74 }
75
76 #[cfg(test)]
77 mod tests {
78 }