elemental_shared/
profile.rs1use crate::{
2 error::Result,
3 loader::Loader,
4 migrator::Migrator,
5 version::{Persistor, VersionControlled, Versioned},
6};
7use serde::{Deserialize, Serialize};
8
9#[derive(Serialize, Deserialize, Default)]
10pub struct Profile<C> {
11 pub config: C,
13 pub version: usize,
14}
15
16impl<C> Versioned for Profile<C> {
17 #[inline(always)]
18 fn version(&self) -> usize {
19 self.version
20 }
21}
22
23impl<C> VersionControlled for Profile<C> {
24 #[inline(always)]
25 fn with_version(mut self, version: usize) -> Self {
26 self.version = version;
27 self
28 }
29}
30
31pub struct ProfileLoader<M, S, C, P>
32where
33 M: Migrator<S, Profile<C>>,
34 S: Versioned,
35 P: Persistor<S>,
36{
37 loader: Loader<M, S, Profile<C>, P>,
38}
39
40impl<M, S, C, P> Clone for ProfileLoader<M, S, C, P>
41where
42 M: Migrator<S, Profile<C>>,
43 S: Versioned,
44 P: Persistor<S>,
45{
46 fn clone(&self) -> Self {
47 Self {
48 loader: self.loader.clone(),
49 }
50 }
51}
52
53impl<M, S, C, P> ProfileLoader<M, S, C, P>
54where
55 M: Migrator<S, Profile<C>>,
56 S: Versioned,
57 C: Default,
58 P: Persistor<S>,
59{
60 pub async fn load(migrator: M, persistor: P, target_version: usize) -> Result<Self> {
61 Ok(Self {
62 loader: Loader::load(migrator, persistor, target_version).await?,
63 })
64 }
65
66 pub async fn cloned(&self) -> C
67 where
68 C: Clone,
69 {
70 self.loader.get(|profile| profile.config.clone()).await
71 }
72
73 pub async fn version(&self) -> usize {
74 self.loader.get(|profile| profile.version).await
75 }
76
77 pub async fn get<T>(&self, f: impl FnOnce(&C) -> T) -> T {
78 self.loader.get(|profile| f(&profile.config)).await
79 }
80
81 pub async fn set(&self, f: impl FnOnce(&mut C)) -> Result<()> {
82 self.loader.set(|profile| f(&mut profile.config)).await
83 }
84}
85
86impl<C: Default> Profile<C> {
87 pub async fn load<M, S, P>(
88 migrator: M,
89 persistor: P,
90 target_version: usize,
91 ) -> Result<ProfileLoader<M, S, C, P>>
92 where
93 S: Versioned,
94 M: Migrator<S, Profile<C>>,
95 P: Persistor<S>,
96 {
97 ProfileLoader::load(migrator, persistor, target_version).await
98 }
99}
100
101impl<C: Clone> Clone for Profile<C> {
102 fn clone(&self) -> Self {
103 Profile {
104 config: self.config.clone(),
105 version: self.version,
106 }
107 }
108}