fd_queue/queue.rs
1// Copyright 2020 Steven Bosnick
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms
8
9use std::error::Error;
10use std::fmt::{self, Display};
11use std::marker::PhantomData;
12use std::os::unix::io::{AsRawFd, RawFd};
13
14/// An interface to enqueue a [`RawFd`][RawFd] for later transmission to a different
15/// process.
16///
17/// This trait is intended to interact with [`Write`][Write] as the mechanism for
18/// actually transmitting the enqueued [`RawFd`][RawFd]. Specifically, the `RawFd`
19/// will be transmitted after a `write()` of at least 1 byte and, possibly, a
20/// `flush()`.
21///
22/// [RawFd]: https://doc.rust-lang.org/stable/std/os/unix/io/type.RawFd.html
23/// [Write]: https://doc.rust-lang.org/stable/std/io/trait.Write.html
24pub trait EnqueueFd {
25 /// Enqueue `fd` for later transmission to a different process.
26 ///
27 /// The caller is responsible for keeping `fd` open until after the `write()` and
28 /// `flush()` calls for actually transmitting the `fd` have been completed.
29 fn enqueue(&mut self, fd: &impl AsRawFd) -> Result<(), QueueFullError>;
30}
31
32/// An interface to dequeue a [`RawFd`][RawFd] that was previously transmitted from a
33/// different process.
34///
35/// This trait is intended to interact with [`Read`][Read] as the mechanism for
36/// actually transmitting the [`RawFd`][RawFd] before it can be dequeued. Specifically
37/// the `RawFd` will become available for dequeuing after at least 1 byte has been
38/// `read()`.
39///
40/// [RawFd]: https://doc.rust-lang.org/stable/std/os/unix/io/type.RawFd.html
41/// [Read]: https://doc.rust-lang.org/stable/std/io/trait.Read.html
42pub trait DequeueFd {
43 /// Dequeue a previously transmitted [`RawFd`][RawFd].
44 ///
45 /// The caller is responsible for closing this `RawFd`.
46 ///
47 /// [RawFd]: https://doc.rust-lang.org/stable/std/os/unix/io/type.RawFd.html
48 fn dequeue(&mut self) -> Option<RawFd>;
49}
50
51/// Error returned when the queue of [`RawFd`][RawFd] is full.
52///
53/// [RawFd]: https://doc.rust-lang.org/stable/std/os/unix/io/type.RawFd.html
54#[derive(Debug, Default)]
55pub struct QueueFullError {
56 _private: PhantomData<()>,
57}
58
59impl QueueFullError {
60 /// Create a new `QueueFullError`.
61 #[inline]
62 pub fn new() -> QueueFullError {
63 QueueFullError {
64 _private: PhantomData,
65 }
66 }
67}
68
69impl Display for QueueFullError {
70 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
71 write!(f, "file descriptor queue is full")
72 }
73}
74
75impl Error for QueueFullError {}