Skip to main content

fast_pull/mem/
pusher.rs

1use crate::{ProgressEntry, Pusher};
2use bytes::Bytes;
3use parking_lot::Mutex;
4use std::{sync::Arc, vec::Vec};
5
6#[derive(Debug, Default, Clone)]
7pub struct MemPusher {
8    pub receive: Arc<Mutex<Vec<u8>>>,
9}
10impl MemPusher {
11    #[must_use]
12    pub fn new() -> Self {
13        Self {
14            receive: Arc::new(Mutex::new(Vec::new())),
15        }
16    }
17    #[must_use]
18    pub fn with_capacity(capacity: usize) -> Self {
19        Self {
20            receive: Arc::new(Mutex::new(Vec::with_capacity(capacity))),
21        }
22    }
23}
24impl Pusher for MemPusher {
25    type Error = ();
26    fn push(&mut self, range: &ProgressEntry, content: Bytes) -> Result<(), (Self::Error, Bytes)> {
27        #![allow(clippy::significant_drop_tightening, clippy::cast_possible_truncation)]
28        let mut guard = self.receive.lock();
29        if range.start as usize == guard.len() {
30            guard.extend_from_slice(&content);
31        } else {
32            if guard.len() < range.end as usize {
33                guard.resize(range.end as usize, 0);
34            }
35            guard[range.start as usize..range.end as usize].copy_from_slice(&content);
36        }
37        Ok(())
38    }
39}