couchbase_core/memdx/
magic.rs1use std::fmt::{Debug, Display};
20
21use crate::memdx::error::Error;
22
23#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum Magic {
26 Req,
27 Res,
28 ReqExt,
29 ResExt,
30
31 ServerReq,
32 ServerRes,
33}
34
35impl Magic {
36 pub fn is_request(&self) -> bool {
37 matches!(self, Magic::Req | Magic::ReqExt)
38 }
39
40 pub fn is_response(&self) -> bool {
41 matches!(self, Magic::Res | Magic::ResExt)
42 }
43
44 pub fn is_extended(&self) -> bool {
45 matches!(self, Magic::ReqExt | Magic::ResExt)
46 }
47}
48
49impl From<Magic> for u8 {
50 fn from(value: Magic) -> u8 {
51 match value {
52 Magic::Req => 0x80,
53 Magic::Res => 0x81,
54 Magic::ReqExt => 0x08,
55 Magic::ResExt => 0x18,
56 Magic::ServerReq => 0x82,
57 Magic::ServerRes => 0x83,
58 }
59 }
60}
61
62impl TryFrom<u8> for Magic {
63 type Error = Error;
64
65 fn try_from(value: u8) -> Result<Self, Self::Error> {
66 let magic = match value {
67 0x80 => Magic::Req,
68 0x81 => Magic::Res,
69 0x08 => Magic::ReqExt,
70 0x18 => Magic::ResExt,
71 0x82 => Magic::ServerReq,
72 0x83 => Magic::ServerRes,
73 _ => {
74 return Err(Error::new_message_error(format!("unknown magic {value}")));
75 }
76 };
77
78 Ok(magic)
79 }
80}
81
82impl Display for Magic {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 let txt = match self {
85 Magic::Req => "Req",
86 Magic::Res => "Res",
87 Magic::ReqExt => "ReqExt",
88 Magic::ResExt => "ResExt",
89 Magic::ServerReq => "ServerReq",
90 Magic::ServerRes => "ServerRes",
91 };
92 write!(f, "{txt}")
93 }
94}