cyfs_bdt/utils/ndn/
mem_store.rs1
2use async_trait::async_trait;
3use std::{
4 collections::BTreeMap,
5 sync::{Arc, RwLock},
6};
7use async_std::{
8 io::Cursor
9};
10use cyfs_base::*;
11use cyfs_util::*;
12use crate::{
13 ndn::{ChunkReader}
14};
15
16struct StoreImpl {
17 chunks: RwLock<BTreeMap<ChunkId, Arc<Vec<u8>>>>
18}
19
20#[derive(Clone)]
21pub struct MemChunkStore(Arc<StoreImpl>);
22
23impl std::fmt::Display for MemChunkStore {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 write!(f, "MemChunkStore")
26 }
27}
28
29impl MemChunkStore {
30 pub fn new() -> Self {
31 Self(Arc::new(StoreImpl {
32 chunks: RwLock::new(BTreeMap::new())
33 }))
34 }
35
36 pub async fn add(&self, id: ChunkId, chunk: Arc<Vec<u8>>) -> BuckyResult<()> {
37 self.0.chunks.write().unwrap().insert(id, chunk);
38 Ok(())
39 }
40
41 pub async fn write_chunk<R: async_std::io::Read + Unpin>(&self, id: &ChunkId, reader: R) -> BuckyResult<()> {
42 let mut buffer = vec![0u8; id.len()];
43 async_std::io::copy(reader, Cursor::new(&mut buffer[..])).await?;
44 self.add(id.clone(), Arc::new(buffer)).await
45 }
46}
47
48
49#[async_trait]
50impl ChunkReader for MemChunkStore {
51 fn clone_as_reader(&self) -> Box<dyn ChunkReader> {
52 Box::new(self.clone())
53 }
54
55 async fn exists(&self, chunk: &ChunkId) -> bool {
56 self.0.chunks.read().unwrap().get(chunk).is_some()
57 }
58
59 async fn get(&self, chunk: &ChunkId) -> BuckyResult<Box<dyn AsyncReadWithSeek + Unpin + Send + Sync>> {
60 let content = self.0.chunks.read().unwrap().get(chunk).cloned()
61 .ok_or_else(|| BuckyError::new(BuckyErrorCode::NotFound, "chunk not exists"))?;
62
63 struct ArcWrap(Arc<Vec<u8>>);
64 impl AsRef<[u8]> for ArcWrap {
65 fn as_ref(&self) -> &[u8] {
66 self.0.as_ref()
67 }
68 }
69
70 Ok(Box::new(Cursor::new(ArcWrap(content))))
71 }
72}
73
74
75
76
77
78
79