xCommonLib/base/
status.rs1use std::error::Error;
2use std::fmt::{self, Display, Formatter};
3
4use serde::{Deserialize, Serialize};
5
6use crate::serial::request_message::RequestMessage;
7
8#[derive(Debug, Serialize, Deserialize)]
9pub struct Status {
10 pub err_code: i32,
11 pub err_msg: String,
12 #[serde(skip)]
13 pub(crate) cached_size: protobuf::rt::CachedSize,
14}
15
16impl Status {
17 pub fn new(err_code: i32, err_msg: String) -> Status {
18 Status {
19 err_code,
20 err_msg,
21 cached_size: protobuf::rt::CachedSize::new(),
22 }
23 }
24
25 pub fn error(err_msg: String) -> Status {
26 Status {
27 err_code: 1,
28 err_msg,
29 cached_size: protobuf::rt::CachedSize::new(),
30 }
31 }
32
33
34 pub fn is_erorr(&self) -> bool {
35 self.err_code != 0
36 }
37
38 pub fn compute_size_with_tag_and_len_return_buffer(&self) -> Vec<u8> {
39 let size = self.compute_size_with_tag_and_len();
40 let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
41 let mut os = protobuf::CodedOutputStream::vec(&mut buffer);
42 self.serial_with_tag_and_len(&mut os);
43 drop(os);
44 buffer
45 }
46}
47
48impl Display for Status {
49 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
50 write!(f, "err_code:{}, err_msg: {}", self.err_code, self.err_msg)
51 }
52}
53
54impl Error for Status {}
55
56impl Default for Status {
57 fn default() -> Self {
58 Status {
59 err_code: 0,
60 err_msg: String::default(),
61 cached_size: protobuf::rt::CachedSize::new(),
62 }
63 }
64}
65
66impl RequestMessage for Status {
67 fn compute_size(&self) -> u64 {
68 let mut my_size = 0;
69 my_size += protobuf::rt::int32_size(1, self.err_code);
70
71 my_size += protobuf::rt::string_size(2, &self.err_msg);
72
73 self.cached_size.set(my_size as u32);
74 my_size
75 }
76
77 fn serial_with_output_stream(
78 &self,
79 os: &mut protobuf::CodedOutputStream<'_>,
80 ) -> Result<(), Status> {
81 os.write_int32(1, self.err_code).unwrap();
82
83 os.write_string(2, &self.err_msg).unwrap();
84
85 Ok(())
86 }
87
88 fn parse_from_input_stream(
89 &mut self,
90 is: &mut protobuf::CodedInputStream<'_>,
91 ) -> Result<(), Status> {
92 while let Some(tag) = is.read_raw_tag_or_eof().unwrap() {
93 match tag {
94 8 => {
95 self.err_code = is.read_int32().unwrap();
96 }
97 18 => {
98 self.err_msg = is.read_string().unwrap();
99 }
100 _ => {}
101 }
102 }
103 Ok(())
104 }
105}