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
//! Session persistence helpers for saving and loading application state.
//!
//! This module provides async convenience functions for serializing application
//! state to JSON files and deserializing it back. All functions require the
//! `serialization` feature.
//!
//! # Example
//!
//! ```rust
//! # tokio_test::block_on(async {
//! use envision::app::persistence::load_state;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Default, PartialEq, Debug)]
//! struct AppState {
//! counter: i32,
//! name: String,
//! }
//!
//! // Save state to a file
//! let dir = std::env::temp_dir().join("envision_doc_test");
//! tokio::fs::create_dir_all(&dir).await.unwrap();
//! let path = dir.join("state.json");
//! let state = AppState { counter: 42, name: "test".into() };
//! let json = serde_json::to_string(&state).unwrap();
//! tokio::fs::write(&path, &json).await.unwrap();
//!
//! // Load it back
//! let loaded: AppState = load_state(&path).await.unwrap();
//! assert_eq!(loaded, state);
//! # tokio::fs::remove_dir_all(&dir).await.unwrap();
//! # });
//! ```
use Path;
use DeserializeOwned;
use crateEnvisionError;
/// Loads application state from a JSON file asynchronously.
///
/// Reads the file at `path` using `tokio::fs`, deserializes it as JSON, and
/// returns the deserialized state.
///
/// # Errors
///
/// Returns [`EnvisionError::Io`] if the file cannot be read (e.g., the file
/// does not exist or permissions are insufficient). Returns
/// [`EnvisionError::Config`] if the file contents cannot be deserialized
/// as valid JSON matching the expected state type.
///
/// # Example
///
/// ```rust
/// # tokio_test::block_on(async {
/// use envision::app::persistence::load_state;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct MyState {
/// count: i32,
/// }
///
/// // Returns EnvisionError::Io for missing files
/// let result: Result<MyState, _> = load_state("/nonexistent/path.json").await;
/// assert!(result.is_err());
/// # });
/// ```
pub async