nmd_core/
resource.rs

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
pub mod disk_resource;
pub mod cached_disk_resource;
pub mod image_resource;
pub mod remote_resource;
pub mod dynamic_resource;
pub mod resource_reference;
pub mod text_reference;
pub mod table;
pub mod source;
pub mod bucket;


use std::{str::FromStr, io::{self}};
use resource_reference::ResourceReferenceError;
use thiserror::Error;


#[derive(Error, Debug)]
pub enum ResourceError {

    #[error("resource '{0}' not found")]
    ResourceNotFound(String),

    #[error("wrong elaboration: '{0}'")]
    WrongElaboration(String),

    #[error("resource is invalid")]
    InvalidResource,

    #[error("resource is invalid because: {0}")]
    InvalidResourceVerbose(String),

    #[error("resource cannot be created: {0}")]
    Creation(String),

    #[error("resource '{0}' cannot be read")]
    ReadError(String),

    #[error(transparent)]
    IoError(#[from] io::Error),
    
    #[error("elaboration error: {0}")]
    ElaborationError(String),

    #[error(transparent)]
    ResourceReferenceError(#[from] ResourceReferenceError),
}

impl Clone for ResourceError {
    fn clone(&self) -> Self {
        match self {
            Self::IoError(e) => Self::ElaborationError(e.to_string()),
            other => other.clone()
        }
    }
}


/// General physical or virtual resource
pub trait Resource: FromStr {

    type LocationType;

    /// write resource content
    fn write(&mut self, content: &str) -> Result<(), ResourceError>;

    /// erase content resource
    fn erase(&mut self) -> Result<(), ResourceError>;

    /// append resource content
    fn append(&mut self, content: &str) -> Result<(), ResourceError>;

    /// read resource content
    fn read(&self) -> Result<String, ResourceError>;

    /// return resource content
    fn content(&self) -> Result<String, ResourceError> {
        self.read()        
    }

    /// return resource name
    fn name(&self) -> &String;

    /// return embedded location type (e.g. PathBuf for files)
    fn location(&self) -> &Self::LocationType;
}