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
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// Wildland Project
//
// Copyright © 2023 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use wildland_corex::dfs::interface::{
    IStream,
    IStreamResult,
    OStream,
    OStreamResult,
    ProgressReporter,
    ProgressUnit,
    StreamErr,
};

pub struct DevShellOStream {
    file: File,
}

impl DevShellOStream {
    pub fn try_new<P: AsRef<Path>>(file_path: P) -> anyhow::Result<Self> {
        let file = File::create(&file_path)?;
        Ok(Self { file })
    }
}

impl OStream for DevShellOStream {
    fn write(&mut self, bytes: Vec<u8>) -> OStreamResult {
        self.file
            .write_all(bytes.as_slice())
            .map_err(|err| StreamErr {
                code: err.raw_os_error().unwrap_or(-1),
                msg: err.to_string(),
            })
    }
}

pub struct DevShellIStream {
    file: File,
    file_size: u64,
}

impl DevShellIStream {
    pub fn try_new<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
        let file = File::open(path)?;
        let file_size = file.metadata()?.len();
        Ok(Self { file, file_size })
    }
}

impl IStream for DevShellIStream {
    fn read(&mut self, bytes_count: usize) -> IStreamResult {
        let mut bytes = Vec::with_capacity(bytes_count);
        std::io::Read::by_ref(&mut self.file)
            .take(bytes_count as _)
            .read_to_end(&mut bytes)
            .map_err(|err| StreamErr {
                code: err.raw_os_error().unwrap_or(-1),
                msg: err.to_string(),
            })?;

        Ok(bytes)
    }

    fn total_size(&self) -> usize {
        self.file_size as _
    }
}

pub struct DevShellProgressReporter {}

impl ProgressReporter for DevShellProgressReporter {
    fn report(&self, completed: usize, total: usize, unit: ProgressUnit) {
        print!("\r{completed} / {total} {unit}\t");
        std::io::stdout().flush().unwrap();
    }
}