Skip to main content

client/region/
codec.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Borrow;
16use std::marker::PhantomData;
17
18use api::v1::region::{RegionRequest, RegionResponse};
19use prost::Message;
20use tonic::Status;
21use tonic::codec::{Codec, EncodeBuf, Encoder};
22use tonic_prost::ProstDecoder;
23
24/// Encodes owned or shared region requests using the existing protobuf wire format.
25pub(crate) struct RegionCodec<R>(PhantomData<R>);
26
27impl<R> Default for RegionCodec<R> {
28    fn default() -> Self {
29        Self(PhantomData)
30    }
31}
32
33impl<R> Codec for RegionCodec<R>
34where
35    R: Borrow<RegionRequest> + Send + 'static,
36{
37    type Encode = R;
38    type Decode = RegionResponse;
39    type Encoder = RegionEncoder<R>;
40    type Decoder = ProstDecoder<RegionResponse>;
41
42    fn encoder(&mut self) -> Self::Encoder {
43        RegionEncoder(PhantomData)
44    }
45
46    fn decoder(&mut self) -> Self::Decoder {
47        ProstDecoder::default()
48    }
49}
50
51/// Borrows the protobuf payload while consuming its owned or shared container.
52pub(crate) struct RegionEncoder<R>(PhantomData<R>);
53
54impl<R: Borrow<RegionRequest>> Encoder for RegionEncoder<R> {
55    type Item = R;
56    type Error = Status;
57
58    fn encode(&mut self, item: R, buf: &mut EncodeBuf<'_>) -> Result<(), Status> {
59        item.borrow()
60            .encode(buf)
61            .map_err(|error| Status::internal(error.to_string()))
62    }
63}