mvdparser/qw/message/
print.rs1use std::fmt::Debug;
2use std::io::{Cursor, Read};
3
4use anyhow::Result;
5
6use crate::qw::primitives::ReadPrimitives;
7use crate::qw::prot::PrintId;
8
9#[derive(PartialEq)]
10pub struct Print {
11 pub id: PrintId,
12 pub content: Vec<u8>,
13}
14
15impl Print {
16 pub fn byte_size(&self) -> usize {
17 self.content.len() + 2 }
19}
20
21impl Debug for Print {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 f.debug_struct("Print")
24 .field("id", &self.id)
25 .field("content", &quake_text::bytestr::to_ascii(&self.content))
26 .finish()
27 }
28}
29
30impl TryFrom<&[u8]> for Print {
31 type Error = std::io::Error;
32
33 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
34 Cursor::new(value).read_print()
35 }
36}
37
38pub trait ReadPrint: ReadPrimitives {
39 fn read_print(&mut self) -> std::io::Result<Print> {
40 Ok(Print {
41 id: PrintId::from(&self.read_byte()?),
42 content: self.read_bstring()?,
43 })
44 }
45}
46
47impl<R: Read + ?Sized> ReadPrint for R {}
48
49#[cfg(test)]
50mod tests {
51 use anyhow::Result;
52 use pretty_assertions::assert_eq;
53
54 use crate::qw::message::Print;
55 use crate::qw::prot::PrintId;
56
57 #[test]
58 fn test_try_from() -> Result<()> {
59 {
61 let data: &[u8] = &[1, 2, 3, 4, 5, 10];
62 assert_eq!(
63 Print::try_from(data).unwrap_err().to_string(),
64 "failed to read string".to_string()
65 );
66 }
67
68 {
70 let data: &[u8] = &[1, 2, 3, 4, 10, 0];
71 let print = Print {
72 id: PrintId::Medium,
73 content: vec![2, 3, 4, 10],
74 };
75 assert_eq!(Print::try_from(data)?, print);
76 assert_eq!(print.byte_size(), 6);
77 }
78
79 Ok(())
80 }
81}