1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use filedesc::FileDesc;

/// Body for the unix tranport.
///
/// The body includes data for a datagram,
/// and a list of file descriptors to attach.
pub struct UnixBody {
	/// The contents for the datagram.
	pub data: Vec<u8>,

	/// The file descriptors to attach.
	pub fds: Vec<FileDesc>,
}

impl UnixBody {
	/// Create a new unix body with datagram contents and file descriptors to attach.
	pub fn new<Data, FileDescs>(data: Data, fds: FileDescs) -> Self
	where
		Vec<u8>: From<Data>,
		Vec<FileDesc>: From<FileDescs>,
	{
		Self {
			data: data.into(),
			fds: fds.into(),
		}
	}
}

impl crate::Body for UnixBody {
	fn empty() -> Self {
		Self::from(Vec::new())
	}

	fn from_error(message: &str) -> Self {
		Self::from(message.as_bytes())
	}

	fn as_error(&self) -> Result<&str, std::str::Utf8Error> {
		std::str::from_utf8(&self.data)
	}

	fn into_error(self) -> Result<String, std::string::FromUtf8Error> {
		String::from_utf8(self.data)
	}
}

impl From<Vec<u8>> for UnixBody {
	fn from(other: Vec<u8>) -> Self {
		Self {
			data: other,
			fds: Vec::new(),
		}
	}
}

impl<'a> From<&'a [u8]> for UnixBody {
	fn from(other: &'a [u8]) -> Self {
		Box::<[u8]>::from(other).into()
	}
}

impl From<Box<[u8]>> for UnixBody {
	fn from(other: Box<[u8]>) -> Self {
		Vec::from(other).into()
	}
}

impl<Data, FileDescs> From<(Data, FileDescs)> for UnixBody
where
	Vec<u8>: From<Data>,
	Vec<FileDesc>: From<FileDescs>,
{
	fn from(other: (Data, FileDescs)) -> Self {
		let (data, fds) = other;
		Self::new(data, fds)
	}
}