nix_compat/wire/ser/
mod.rs1use std::error::Error as StdError;
2use std::future::Future;
3use std::{fmt, io};
4
5use super::ProtocolVersion;
6
7mod bytes;
8mod collections;
9mod int;
10mod writer;
11
12pub use writer::{NixWriter, NixWriterBuilder};
13
14pub trait Error: Sized + StdError {
15 fn custom<T: fmt::Display>(msg: T) -> Self;
16
17 fn io_error(err: std::io::Error) -> Self {
18 Self::custom(format_args!("There was an I/O error {err}"))
19 }
20
21 fn unsupported_data<T: fmt::Display>(msg: T) -> Self {
22 Self::custom(msg)
23 }
24
25 fn invalid_enum<T: fmt::Display>(msg: T) -> Self {
26 Self::custom(msg)
27 }
28}
29
30impl Error for io::Error {
31 fn custom<T: fmt::Display>(msg: T) -> Self {
32 io::Error::other(msg.to_string())
33 }
34
35 fn io_error(err: std::io::Error) -> Self {
36 err
37 }
38
39 fn unsupported_data<T: fmt::Display>(msg: T) -> Self {
40 io::Error::new(io::ErrorKind::InvalidData, msg.to_string())
41 }
42}
43
44pub trait NixWrite: Send {
45 type Error: Error;
46
47 fn version(&self) -> ProtocolVersion;
50
51 fn write_number(&mut self, value: u64) -> impl Future<Output = Result<(), Self::Error>> + Send;
53
54 fn write_slice(&mut self, buf: &[u8]) -> impl Future<Output = Result<(), Self::Error>> + Send;
56
57 fn write_display<D>(&mut self, msg: D) -> impl Future<Output = Result<(), Self::Error>> + Send
62 where
63 D: fmt::Display + Send,
64 Self: Sized,
65 {
66 async move {
67 let s = msg.to_string();
68 self.write_slice(s.as_bytes()).await
69 }
70 }
71
72 fn write_value<V>(&mut self, value: &V) -> impl Future<Output = Result<(), Self::Error>> + Send
75 where
76 V: NixSerialize + Send + ?Sized,
77 Self: Sized,
78 {
79 value.serialize(self)
80 }
81}
82
83impl<T: NixWrite> NixWrite for &mut T {
84 type Error = T::Error;
85
86 fn version(&self) -> ProtocolVersion {
87 (**self).version()
88 }
89
90 fn write_number(&mut self, value: u64) -> impl Future<Output = Result<(), Self::Error>> + Send {
91 (**self).write_number(value)
92 }
93
94 fn write_slice(&mut self, buf: &[u8]) -> impl Future<Output = Result<(), Self::Error>> + Send {
95 (**self).write_slice(buf)
96 }
97
98 fn write_display<D>(&mut self, msg: D) -> impl Future<Output = Result<(), Self::Error>> + Send
99 where
100 D: fmt::Display + Send,
101 Self: Sized,
102 {
103 (**self).write_display(msg)
104 }
105
106 fn write_value<V>(&mut self, value: &V) -> impl Future<Output = Result<(), Self::Error>> + Send
107 where
108 V: NixSerialize + Send + ?Sized,
109 Self: Sized,
110 {
111 (**self).write_value(value)
112 }
113}
114
115pub trait NixSerialize {
116 fn serialize<W>(&self, writer: &mut W) -> impl Future<Output = Result<(), W::Error>> + Send
118 where
119 W: NixWrite;
120}
121
122impl NixSerialize for () {
124 async fn serialize<W>(&self, _writer: &mut W) -> Result<(), W::Error>
125 where
126 W: NixWrite,
127 {
128 Ok(())
129 }
130}