Skip to main content

couchbase_core/memdx/
magic.rs

1/*
2 *
3 *  * Copyright (c) 2025 Couchbase, Inc.
4 *  *
5 *  * Licensed under the Apache License, Version 2.0 (the "License");
6 *  * you may not use this file except in compliance with the License.
7 *  * You may obtain a copy of the License at
8 *  *
9 *  *    http://www.apache.org/licenses/LICENSE-2.0
10 *  *
11 *  * Unless required by applicable law or agreed to in writing, software
12 *  * distributed under the License is distributed on an "AS IS" BASIS,
13 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  * See the License for the specific language governing permissions and
15 *  * limitations under the License.
16 *
17 */
18
19use 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}