Skip to main content

fast_pull/mem/
pusher.rs

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