Skip to content

Commit 786c3d0

Browse files
committed
Add impl AsFd variants of the <Fd: AsFd> examples.
1 parent 53b0ed1 commit 786c3d0

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

examples/flexible-apis.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ fn use_fd_b<Fd: AsFd>(fd: Fd) {
3131
let _ = fd.as_fd();
3232
}
3333

34+
/// Another way to do this is to use an `impl AsFd` parameter.
35+
#[cfg(all(feature = "close", not(windows)))]
36+
fn use_fd_c(fd: impl AsFd) {
37+
let _ = fd.as_fd();
38+
}
39+
3440
/// The simplest way to accept a consumed I/O resource is to simply use an
3541
/// `OwnedFd` as an argument. Similar to `use_fd_a`, this doesn't require the
3642
/// function to have any type parameters, and also works in FFI signatures.
@@ -51,6 +57,12 @@ fn consume_fd_b<Fd: IntoFd>(fd: Fd) {
5157
let _ = fd.into_fd();
5258
}
5359

60+
/// Another way to do this is to use an `impl IntoFd` parameter.
61+
#[cfg(all(feature = "close", not(windows)))]
62+
fn consume_fd_c(fd: impl IntoFd) {
63+
let _ = fd.into_fd();
64+
}
65+
5466
/// Now let's see how the APIs look for users.
5567
#[cfg(all(feature = "close", not(windows)))]
5668
fn main() {
@@ -59,20 +71,30 @@ fn main() {
5971
// The simple option requires an `.as_fd()` at the callsite.
6072
use_fd_a(f.as_fd());
6173

62-
// The other option can take a reference to any owning type directly.
74+
// Another option can take a reference to any owning type directly.
6375
use_fd_b(&f);
6476

6577
// Of course, users can still pass in `BorrowedFd` values if they want to.
6678
use_fd_b(f.as_fd());
6779

80+
// The other option is `impl AsFd`.
81+
use_fd_c(&f);
82+
83+
// Users can still pass in `BorrowedFd` values if they want to here too.
84+
use_fd_c(f.as_fd());
85+
6886
let a = std::fs::File::open("Cargo.toml").unwrap();
6987
let b = std::fs::File::open("Cargo.toml").unwrap();
88+
let c = std::fs::File::open("Cargo.toml").unwrap();
7089

7190
// The simple option requires an `.into_fd()` at the callsite.
7291
consume_fd_a(a.into_fd());
7392

74-
// The other option can take any `IntoFd` type directly.
93+
// Another option can take any `IntoFd` type directly.
7594
consume_fd_b(b);
95+
96+
// The other option can take any `IntoFd` type directly.
97+
consume_fd_c(c);
7698
}
7799

78100
#[cfg(windows)]

0 commit comments

Comments
 (0)