Debian Codegraph @

debian/rust-vendor/filedescriptor/README.md

raw
1 <!-- cargo-sync-readme start -->
2
3 The purpose of this crate is to make it a bit more ergonomic for portable
4 applications that need to work with the platform level `RawFd` and
5 `RawHandle` types.
6
7 Rather than conditionally using `RawFd` and `RawHandle`, the `FileDescriptor`
8 type can be used to manage ownership, duplicate, read and write.
9
10 ## FileDescriptor
11
12 This is a bit of a contrived example, but demonstrates how to avoid
13 the conditional code that would otherwise be required to deal with
14 calling `as_raw_fd` and `as_raw_handle`:
15
16 ```
17 use filedescriptor::{FileDescriptor, FromRawFileDescriptor, Result};
18 use std::io::Write;
19
20 fn get_stdout() -> Result<FileDescriptor> {
21 let stdout = std::io::stdout();
22 let handle = stdout.lock();
23 FileDescriptor::dup(&handle)
24 }
25
26 fn print_something() -> Result<()> {
27 get_stdout()?.write(b"hello")?;
28 Ok(())
29 }
30 ```
31
32 ## Pipe
33 The `Pipe` type makes it more convenient to create a pipe and manage
34 the lifetime of both the read and write ends of that pipe.
35
36 ```
37 use filedescriptor::Pipe;
38 use std::io::{Read, Write};
39
40 let mut pipe = Pipe::new()?;
41 pipe.write.write(b"hello")?;
42 drop(pipe.write);
43
44 let mut s = String::new();
45 pipe.read.read_to_string(&mut s)?;
46 assert_eq!(s, "hello");
47 ```
48
49 ## Socketpair
50 The `socketpair` function returns a pair of connected `SOCK_STREAM`
51 sockets and functions both on posix and windows systems.
52
53 ```
54 use std::io::{Read, Write};
55
56 let (mut a, mut b) = filedescriptor::socketpair()?;
57 a.write(b"hello")?;
58 drop(a);
59
60 let mut s = String::new();
61 b.read_to_string(&mut s)?;
62 assert_eq!(s, "hello");
63 ```
64
65 ## Polling
66 The `mio` crate offers powerful and scalable IO multiplexing, but there
67 are some situations where `mio` doesn't fit. The `filedescriptor` crate
68 offers a `poll(2)` compatible interface suitable for testing the readiness
69 of a set of file descriptors. On unix systems this is a very thin wrapper
70 around `poll(2)`, except on macOS where it is actually a wrapper around
71 the `select(2)` interface. On Windows systems the winsock `WSAPoll`
72 function is used instead.
73
74 ```
75 use filedescriptor::*;
76 use std::time::Duration;
77 use std::io::{Read, Write};
78
79 let (mut a, mut b) = filedescriptor::socketpair()?;
80 let mut poll_array = [pollfd {
81 fd: a.as_socket_descriptor(),
82 events: POLLIN,
83 revents: 0
84 }];
85 // sleeps for 20 milliseconds because `a` is not yet ready
86 assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 0);
87
88 b.write(b"hello")?;
89
90 // Now a is ready for read
91 assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 1);
92
93 ```
94
95 <!-- cargo-sync-readme end -->