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
//
// 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 serde::{Deserialize, Serialize};
use thiserror::Error;

pub trait SpecialFileOperations {
    fn create_special_file(
        &mut self,
        file_name: String,
        file_type: SpecialFileType,
        input: Option<Vec<u8>>,
    ) -> SfoResult<()>;

    fn remove_special_file(
        &mut self,
        file_name: String,
        file_type: SpecialFileType,
    ) -> SfoResult<()>;

    fn write_to_special_file(
        &self,
        file_name: String,
        file_type: SpecialFileType,
        contents: Vec<u8>,
        append: bool,
    ) -> SfoResult<()>;

    fn read_from_special_file(
        &self,
        file_name: String,
        file_type: SpecialFileType,
    ) -> SfoResult<Vec<u8>>;

    fn get_special_file_path(
        &self,
        file_name: String,
        file_type: SpecialFileType,
    ) -> SfoResult<String>;
}

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub enum SpecialFileType {
    Data,
    Cache,
    Temporary,
}

impl TryFrom<String> for SpecialFileType {
    type Error = SfoError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.to_ascii_lowercase().as_str() {
            "data" => Ok(SpecialFileType::Data),
            "cache" => Ok(SpecialFileType::Cache),
            "temporary" | "temp" | "tmp" => Ok(SpecialFileType::Temporary),
            _ => Err(SfoError::Generic(format!(
                "Could not create SpecialFileType from {}",
                value
            ))),
        }
    }
}

#[derive(Error, Debug, PartialEq, Eq, Clone)]
#[repr(C)]
pub enum SfoError {
    #[error("Special File Operations error: {0}")]
    Generic(String),
    #[error("Special file already exists")]
    FileExists,
    #[error("Special file not found")]
    FileNotFound,
}

pub type SfoResult<T> = Result<T, SfoError>;