common_datasource/share_buffer.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::io::Write;
16use std::sync::{Arc, Mutex};
17
18use bytes::{BufMut, BytesMut};
19
20#[derive(Clone, Default)]
21pub struct SharedBuffer {
22 pub buffer: Arc<Mutex<BytesMut>>,
23}
24
25impl SharedBuffer {
26 pub fn with_capacity(size: usize) -> Self {
27 Self {
28 buffer: Arc::new(Mutex::new(BytesMut::with_capacity(size))),
29 }
30 }
31}
32
33impl Write for SharedBuffer {
34 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
35 let len = buf.len();
36 let mut buffer = self.buffer.lock().unwrap();
37 buffer.put_slice(buf);
38 Ok(len)
39 }
40
41 fn flush(&mut self) -> std::io::Result<()> {
42 // This flush implementation is intentionally left to blank.
43 // The actual flush is in `BufferedWriter::try_flush`
44 Ok(())
45 }
46}