1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::error::Result;
use std::{
    collections::HashMap,
    fs, io,
    path::{Path, PathBuf},
    sync,
};

pub trait FileCreator {
    type Writer: io::Write;

    fn create(&mut self, path: &Path) -> Result<Self::Writer>;
}

pub struct FsFileCreator;

impl FileCreator for FsFileCreator {
    type Writer = fs::File;

    fn create(&mut self, path: &Path) -> Result<Self::Writer> {
        match path.parent() {
            Some(dir) => fs::create_dir_all(dir)?,
            None => (),
        }

        Ok(fs::File::create(path)?)
    }
}

impl FsFileCreator {
    pub fn new() -> Self {
        Self
    }
}

pub struct BufFileCreator {
    files: HashMap<PathBuf, sync::Arc<sync::Mutex<Vec<u8>>>>,
}

pub struct BufFileWriter(sync::Arc<sync::Mutex<Vec<u8>>>);

impl BufFileWriter {
    fn get_for_io(&mut self) -> io::Result<sync::MutexGuard<Vec<u8>>> {
        self.0.try_lock().map_err(|e| match e {
            sync::TryLockError::Poisoned(_) => {
                io::Error::new(io::ErrorKind::BrokenPipe, "BufFileWriter: Mutex Poisoned")
            }
            sync::TryLockError::WouldBlock => io::Error::new(
                io::ErrorKind::WouldBlock,
                "BufFileWriter: Mutex would block",
            ),
        })
    }

    fn new(inner: sync::Arc<sync::Mutex<Vec<u8>>>) -> Self {
        Self(inner)
    }
}

impl io::Write for BufFileWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.get_for_io()?.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.get_for_io()?.flush()
    }
}

impl FileCreator for BufFileCreator {
    type Writer = BufFileWriter;

    fn create(&mut self, path: &Path) -> Result<Self::Writer> {
        self.files.insert(
            path.to_path_buf(),
            sync::Arc::new(sync::Mutex::new(Vec::new())),
        );

        Ok(BufFileWriter::new(self.files.get(path).unwrap().clone()))
    }
}