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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use super::*;
use getset::{CopyGetters, Getters, MutGetters};
use serde::Serialize;
use std::cell::RefCell;
use std::fmt::{self, Display};

/// # A structure to hold the root document as well as its state.
#[derive(Debug, Getters, MutGetters, CopyGetters)]
pub struct SparseRoot<S: DeserializeOwned + Serialize + SparsableTrait> {
    #[getset(get = "pub(crate)", get_mut = "pub(crate)")]
    val: S,
    #[getset(get = "pub")]
    state: Rc<RefCell<SparseState>>,
    #[getset(get = "pub")]
    metadata: SparseMetadata,
}

impl<S> fmt::Display for SparseRoot<S>
where
    S: DeserializeOwned + Serialize + SparsableTrait + Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.val)
    }
}

impl<S> SparseRoot<S>
where
    S: DeserializeOwned + Serialize + SparsableTrait,
{
    /// Get the value this selector is managing, either by deserializing
    /// the pointed value or by directly returning the owned value.
    pub fn check_version(&'_ self) -> Result<(), SparseError> {
        let state = self
            .state
            .try_borrow()
            .map_err(|_x| SparseError::StateAlreadyBorrowed)?;
        let root_file: &SparseStateFile = state
            .get_state_file(state.get_root_path())
            .map_err(|_e| SparseError::NoRoot)?;
        match root_file.version() == self.metadata().version() {
            true => Ok(()),
            false => Err(SparseError::OutdatedPointer),
        }
    }

    /// Get the value this selector is managing, either by deserializing
    /// the pointed value or by directly returning the owned value.
    pub fn root_get(&self) -> Result<SparseValue<'_, S>, SparseError> {
        Ok(SparseValue::new(&self.val, Some(&self.metadata)))
    }

    /// Like `root_get` but return a mutable reference
    pub fn root_get_mut(&mut self) -> Result<SparseValueMut<'_, S>, SparseError> {
        let state = self.state().clone();
        self.check_version()?;
        SparseValueMut::new_root(self.val_mut(), state)
    }

    /// Reset the root object in case of initialization or update
    pub fn root_self_reset(&mut self) -> Result<(), SparseError> {
        {
            let state = self
                .state
                .try_borrow()
                .map_err(|_x| SparseError::StateAlreadyBorrowed)?;
            let root_file: &SparseStateFile = state
                .get_state_file(state.get_root_path())
                .map_err(|_e| SparseError::NoRoot)?;
            self.val = serde_json::from_value(root_file.val().clone())?;
        }
        self.sparse_init()
    }

    /// Intitialize the inner state
    pub fn sparse_init(&mut self) -> Result<(), SparseError> {
        self.val.sparse_init(
            &mut *self
                .state
                .try_borrow_mut()
                .map_err(|_x| SparseError::StateAlreadyBorrowed)?,
            &self.metadata().clone(),
            0,
        )
    }

    /// Update the inner state
    pub fn sparse_updt(&mut self) -> Result<(), SparseError> {
        let vcheck = self.check_version();
        match vcheck {
            Ok(()) => Ok(()),
            Err(SparseError::OutdatedPointer) => {
                self.root_self_reset()?;
                self.sparse_init()
            }
            Err(_) => vcheck,
        }
    }

    /// Create a new [SparseRoot](crate::SparseRoot) from file path
    pub fn new_from_file(path: PathBuf) -> Result<Self, SparseError> {
        let mut state: SparseState = SparseState::new_from_file(path)?;
        let val: S = state.parse_root()?;
        let root_path = state.get_root_path().clone();
        let version: u64 = state.get_state_file(&root_path)?.version();
        let mut metadata = SparseMetadata::new(String::from("/"), root_path);

        *metadata.version_mut() = version;
        Ok(SparseRoot {
            val,
            state: Rc::new(RefCell::new(state)),
            metadata,
        })
    }

    /// Create a new [SparseRoot](crate::SparseRoot) from a Value object
    pub fn new_from_value(
        rval: Value,
        path: PathBuf,
        others: Vec<(Value, PathBuf)>,
    ) -> Result<Self, SparseError> {
        let mut state: SparseState = SparseState::new_from_value(path, rval)?;
        let root_path = state.get_root_path().clone();
        let version: u64 = state.get_state_file(&root_path)?.version();
        for (val, path) in others.into_iter() {
            state.add_value(path, val)?;
        }
        let val = state.parse_root()?;
        let mut metadata = SparseMetadata::new(String::from("/"), root_path);

        *metadata.version_mut() = version;
        Ok(SparseRoot {
            val,
            state: Rc::new(RefCell::new(state)),
            metadata,
        })
    }

    /// Create a new [SparseRoot](crate::SparseRoot) from a serialized object
    pub fn new_from_obj(
        rval: S,
        path: PathBuf,
        others: Vec<(&mut S, PathBuf)>,
    ) -> Result<Self, SparseError> {
        let mut state: SparseState =
            SparseState::new_from_value(path.clone(), serde_json::to_value(rval)?)?;
        for (val, path) in others.into_iter() {
            state.add_obj(path, val)?;
        }
        let val: S = state.parse_file(path.clone())?;
        let version: u64 = state.get_state_file(state.get_root_path())?.version();
        let mut metadata = SparseMetadata::new(String::from("/"), path);

        *metadata.version_mut() = version;
        Ok(SparseRoot {
            val,
            state: Rc::new(RefCell::new(state)),
            metadata,
        })
    }

    /// Save the state to disk in the specified format.
    /// If not format is specified, the format in which the document was read will be used.
    /// If the document was read from memory, it'll be written in prettified JSON
    pub fn save_to_disk(&self, format: Option<SparseFileFormat>) -> Result<(), SparseError> {
        self.state
            .try_borrow()
            .map_err(|_e| SparseError::StateAlreadyBorrowed)?
            .save_to_disk(format)
    }
}