nix_compat/wire/de/
bytes.rs1use bytes::Bytes;
2
3use super::{Error, NixDeserialize, NixRead};
4
5impl NixDeserialize for Bytes {
6 async fn try_deserialize<R>(reader: &mut R) -> Result<Option<Self>, R::Error>
7 where
8 R: ?Sized + NixRead + Send,
9 {
10 reader.try_read_bytes().await
11 }
12}
13
14impl NixDeserialize for String {
15 async fn try_deserialize<R>(reader: &mut R) -> Result<Option<Self>, R::Error>
16 where
17 R: ?Sized + NixRead + Send,
18 {
19 if let Some(buf) = reader.try_read_bytes().await? {
20 String::from_utf8(buf.to_vec())
21 .map_err(R::Error::invalid_data)
22 .map(Some)
23 } else {
24 Ok(None)
25 }
26 }
27}
28
29#[cfg(test)]
30mod test {
31 use std::io;
32
33 use hex_literal::hex;
34 use rstest::rstest;
35 use tokio_test::io::Builder;
36
37 use crate::wire::de::{NixRead, NixReader};
38
39 #[rstest]
40 #[case::empty("", &hex!("0000 0000 0000 0000"))]
41 #[case::one(")", &hex!("0100 0000 0000 0000 2900 0000 0000 0000"))]
42 #[case::two("it", &hex!("0200 0000 0000 0000 6974 0000 0000 0000"))]
43 #[case::three("tea", &hex!("0300 0000 0000 0000 7465 6100 0000 0000"))]
44 #[case::four("were", &hex!("0400 0000 0000 0000 7765 7265 0000 0000"))]
45 #[case::five("where", &hex!("0500 0000 0000 0000 7768 6572 6500 0000"))]
46 #[case::six("unwrap", &hex!("0600 0000 0000 0000 756E 7772 6170 0000"))]
47 #[case::seven("where's", &hex!("0700 0000 0000 0000 7768 6572 6527 7300"))]
48 #[case::aligned("read_tea", &hex!("0800 0000 0000 0000 7265 6164 5F74 6561"))]
49 #[case::more_bytes("read_tess", &hex!("0900 0000 0000 0000 7265 6164 5F74 6573 7300 0000 0000 0000"))]
50 #[case::utf8("The quick brown 🦊 jumps over 13 lazy 🐶.", &hex!("2D00 0000 0000 0000 5468 6520 7175 6963 6b20 6272 6f77 6e20 f09f a68a 206a 756d 7073 206f 7665 7220 3133 206c 617a 7920 f09f 90b6 2e00 0000"))]
51 #[tokio::test]
52 async fn test_read_string(#[case] expected: &str, #[case] data: &[u8]) {
53 let mock = Builder::new().read(data).build();
54 let mut reader = NixReader::new(mock);
55 let actual: String = reader.read_value().await.unwrap();
56 assert_eq!(actual, expected);
57 }
58
59 #[tokio::test]
60 async fn test_read_string_invalid() {
61 let mock = Builder::new()
62 .read(&hex!("0300 0000 0000 0000 EDA0 8000 0000 0000"))
63 .build();
64 let mut reader = NixReader::new(mock);
65 assert_eq!(
66 io::ErrorKind::InvalidData,
67 reader.read_value::<String>().await.unwrap_err().kind()
68 );
69 }
70}