summaryrefslogtreecommitdiff
path: root/rola-vcs/src/abstracts/dir_pointer.rs
blob: 0e59960f56024783097fe8fed6c804c5056258b2 (plain) (blame)
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
use std::{
    borrow::Borrow,
    ops::{Deref, DerefMut},
    path::PathBuf,
};

/// Directory Pointer Data
pub trait DirPtrData {
    /// Fix the given path
    ///
    /// Returns Some(path): use the fixed path
    /// Returns None: path cannot be fixed, this pointer is invalid
    #[doc(hidden)]
    fn fix(raw_path: PathBuf) -> Option<PathBuf>;
}

#[derive(Debug, Default, Clone)]
pub struct DirPtr<Data: DirPtrData> {
    /// Whether the current directory pointer is valid
    valid: bool,

    /// Data for the directory pointer
    data: Data,

    /// Path to the directory
    path: PathBuf,
}

impl<Data: DirPtrData> DirPtr<Data> {
    /// Get a reference to the directory pointer's path
    pub fn path_ref(&self) -> &PathBuf {
        &self.path
    }

    /// Get the directory pointer's path
    pub fn path(&self) -> PathBuf {
        self.path.clone()
    }

    /// Returns whether the directory pointer is valid
    pub fn is_valid(&self) -> bool {
        self.valid
    }
}

impl<Data: DirPtrData + Default> DirPtr<Data> {
    /// Create a new directory pointer with the given path and default data
    pub fn new(path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        let fixed = Data::fix(path.clone());
        Self {
            valid: fixed.is_some(),
            data: Data::default(),
            path: fixed.unwrap_or(path),
        }
    }
}

impl<Data: DirPtrData> AsRef<DirPtr<Data>> for DirPtr<Data> {
    fn as_ref(&self) -> &DirPtr<Data> {
        self
    }
}

impl<Data: DirPtrData> Deref for DirPtr<Data> {
    type Target = Data;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<Data: DirPtrData> DerefMut for DirPtr<Data> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl<Data: DirPtrData> Borrow<Data> for DirPtr<Data> {
    fn borrow(&self) -> &Data {
        &self.data
    }
}

/// Create a new directory pointer with the given path and default data
pub fn dir_ptr<Data: DirPtrData + Default>(path: impl Into<PathBuf>) -> DirPtr<Data> {
    DirPtr::new(path)
}