mick_jaeger/
glue.rs

1// Copyright (C) 2020 Pierre Krieger
2// SPDX-License-Identifier: Apache-2.0
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// Copied from https://github.com/open-telemetry/opentelemetry-rust/tree/master/opentelemetry-jaeger/src/transport
17
18use std::{
19    io,
20    sync::{Arc, Mutex},
21};
22
23#[derive(Debug)]
24pub(crate) struct TNoopChannel;
25
26impl io::Read for TNoopChannel {
27    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
28        Ok(0)
29    }
30}
31
32#[derive(Debug, Clone)]
33pub(crate) struct TBufferChannel {
34    inner: Arc<Mutex<Vec<u8>>>,
35}
36
37impl TBufferChannel {
38    pub fn with_capacity(capacity: usize) -> Self {
39        TBufferChannel {
40            inner: Arc::new(Mutex::new(Vec::with_capacity(capacity))),
41        }
42    }
43
44    pub fn take_bytes(&mut self) -> Vec<u8> {
45        self.inner
46            .lock()
47            .map(|mut write| write.split_off(0))
48            .unwrap_or_default()
49    }
50}
51
52impl io::Read for TBufferChannel {
53    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
54        unreachable!("jaeger protocol never reads")
55    }
56}
57
58impl io::Write for TBufferChannel {
59    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
60        if let Ok(mut inner) = self.inner.lock() {
61            inner.extend_from_slice(buf);
62        }
63        Ok(buf.len())
64    }
65
66    fn flush(&mut self) -> io::Result<()> {
67        Ok(())
68    }
69}
70
71impl thrift::transport::TIoChannel for TBufferChannel {
72    fn split(
73        self,
74    ) -> thrift::Result<(
75        thrift::transport::ReadHalf<Self>,
76        thrift::transport::WriteHalf<Self>,
77    )>
78    where
79        Self: Sized,
80    {
81        Ok((
82            thrift::transport::ReadHalf::new(self.clone()),
83            thrift::transport::WriteHalf::new(self),
84        ))
85    }
86}