fbthrift_git/
thrift_protocol.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use num_derive::FromPrimitive;
18use num_traits::FromPrimitive;
19
20use crate::errors::ProtocolError;
21use crate::Result;
22
23/// Protocol kind. int16
24#[repr(i16)]
25#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, FromPrimitive)]
26pub enum ProtocolID {
27    BinaryProtocol = 0,
28    JSONProtocol = 1,
29    CompactProtocol = 2,
30    DebugProtocol = 3,
31    VirtualProtocol = 4,
32    SimpleJSONProtocol = 5,
33}
34
35impl TryFrom<i16> for ProtocolID {
36    type Error = anyhow::Error;
37
38    fn try_from(val: i16) -> Result<Self> {
39        match ProtocolID::from_i16(val) {
40            Some(id) => Ok(id),
41            None => bail_err!(ProtocolError::InvalidProtocolID(val)),
42        }
43    }
44}
45
46impl From<ProtocolID> for &'static str {
47    fn from(t: ProtocolID) -> &'static str {
48        match t {
49            ProtocolID::BinaryProtocol => "binary",
50            ProtocolID::JSONProtocol => "json",
51            ProtocolID::CompactProtocol => "compact",
52            ProtocolID::DebugProtocol => "debug",
53            ProtocolID::VirtualProtocol => "virtual",
54            ProtocolID::SimpleJSONProtocol => "simplejson",
55        }
56    }
57}
58
59/// Message type constants in the Thrift protocol, treated as i32 in golang
60#[derive(Debug, Copy, Clone, Eq, PartialEq, FromPrimitive)]
61#[repr(u32)]
62pub enum MessageType {
63    InvalidMessageType = 0,
64    Call = 1,
65    Reply = 2,
66    Exception = 3,
67    Oneway = 4, // Unused
68}
69
70impl TryFrom<u32> for MessageType {
71    type Error = anyhow::Error;
72
73    fn try_from(val: u32) -> Result<Self> {
74        match MessageType::from_u32(val) {
75            Some(t) => Ok(t),
76            None => bail_err!(ProtocolError::InvalidMessageType(val)),
77        }
78    }
79}