Skip to main content

ferrix_app/
load_state.rs

1/* load_state.rs
2 *
3 * Copyright 2025 Michail Krasnov <mskrasnov07@ya.ru>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21//! Data loading states
22
23use serde::{Deserialize, Serialize};
24
25pub type DataLoadingState<P> = LoadState<P>;
26
27#[derive(Debug, Deserialize, Serialize, Clone, Default)]
28#[serde(untagged)]
29pub enum LoadState<P> {
30    #[default]
31    Loading,
32    Error(String), // TODO: replace `String` to `crate::error::Error`
33    Loaded(P),
34}
35
36impl<P> LoadState<P> {
37    pub fn to_option<'a>(&'a self) -> Option<&'a P> {
38        match self {
39            Self::Loaded(data) => Some(data),
40            _ => None,
41        }
42    }
43
44    pub fn is_none(&self) -> bool {
45        match self {
46            Self::Loaded(_) => false,
47            _ => true,
48        }
49    }
50
51    pub fn is_some(&self) -> bool {
52        !self.is_none()
53    }
54
55    pub fn some_value(&self) -> bool {
56        match self {
57            Self::Loading => false,
58            _ => true,
59        }
60    }
61
62    pub fn is_error(&self) -> bool {
63        match self {
64            Self::Error(_) => true,
65            _ => false,
66        }
67    }
68
69    pub fn unwrap(&self) -> &P {
70        self.to_option().unwrap()
71    }
72}
73
74pub trait ToLoadState<P> {
75    fn to_load_state(self) -> LoadState<P>;
76}
77
78impl<P> ToLoadState<P> for anyhow::Result<P> {
79    fn to_load_state(self) -> LoadState<P> {
80        match self {
81            Self::Ok(data) => LoadState::Loaded(data),
82            Self::Err(why) => LoadState::Error(why.to_string()),
83        }
84    }
85}