1 |
use std::{
|
2 |
fmt::{Debug, Display},
|
3 |
marker::PhantomData,
|
4 |
str::FromStr,
|
5 |
};
|
6 |
|
7 |
use anyhow::Error;
|
8 |
|
9 |
use crate::{
|
10 |
error::{GetValueError, OperationError},
|
11 |
object_backend::ObjectBackend,
|
12 |
operation::GiteratedOperation,
|
13 |
settings::{GetSetting, GetSettingError, SetSetting, SetSettingError, Setting},
|
14 |
value::{GetValue, GiteratedObjectValue},
|
15 |
};
|
16 |
|
17 |
mod operations;
|
18 |
pub use operations::*;
|
19 |
|
20 |
#[derive(Debug, Clone)]
|
21 |
pub struct Object<'b, O: GiteratedObject, B: ObjectBackend + 'b + Send + Sync + Clone> {
|
22 |
pub(crate) inner: O,
|
23 |
pub(crate) backend: B,
|
24 |
pub(crate) _marker: PhantomData<&'b ()>,
|
25 |
}
|
26 |
|
27 |
impl<'b, B: ObjectBackend + Send + Sync + Clone, O: GiteratedObject> Object<'b, O, B> {
|
28 |
pub fn object(&self) -> &O {
|
29 |
&self.inner
|
30 |
}
|
31 |
|
32 |
pub unsafe fn new_unchecked(object: O, backend: B) -> Object<'b, O, B> {
|
33 |
Object {
|
34 |
inner: object,
|
35 |
backend,
|
36 |
_marker: PhantomData,
|
37 |
}
|
38 |
}
|
39 |
}
|
40 |
|
41 |
impl<O: GiteratedObject + Display, B: ObjectBackend + Send + Sync + Clone> Display
|
42 |
for Object<'_, O, B>
|
43 |
{
|
44 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
45 |
self.inner.fmt(f)
|
46 |
}
|
47 |
}
|
48 |
|
49 |
pub trait GiteratedObject: Send + Display + FromStr {
|
50 |
fn object_name() -> &'static str;
|
51 |
|
52 |
fn from_object_str(object_str: &str) -> Result<Self, Error>;
|
53 |
}
|
54 |
|
55 |
impl<'b, O: GiteratedObject + Clone + Debug, B: ObjectBackend> Object<'b, O, B> {
|
56 |
pub async fn get<V: GiteratedObjectValue<Object = O> + Send + Debug>(
|
57 |
&mut self,
|
58 |
) -> Result<V, OperationError<GetValueError>> {
|
59 |
self.request(GetValue {
|
60 |
value_name: V::value_name().to_string(),
|
61 |
_marker: PhantomData,
|
62 |
})
|
63 |
.await
|
64 |
}
|
65 |
|
66 |
pub async fn get_setting<S: Setting + Send + Clone + Debug>(
|
67 |
&mut self,
|
68 |
) -> Result<S, OperationError<GetSettingError>> {
|
69 |
self.request(GetSetting {
|
70 |
setting_name: S::name().to_string(),
|
71 |
_marker: PhantomData,
|
72 |
})
|
73 |
.await
|
74 |
}
|
75 |
|
76 |
pub async fn set_setting<S: Setting + Send + Clone + Debug>(
|
77 |
&mut self,
|
78 |
setting: S,
|
79 |
) -> Result<(), OperationError<SetSettingError>> {
|
80 |
self.request(SetSetting {
|
81 |
setting_name: S::name().to_string(),
|
82 |
value: setting,
|
83 |
})
|
84 |
.await
|
85 |
}
|
86 |
|
87 |
pub async fn request<R: GiteratedOperation<O> + Debug>(
|
88 |
&mut self,
|
89 |
request: R,
|
90 |
) -> Result<R::Success, OperationError<R::Failure>> {
|
91 |
self.backend
|
92 |
.object_operation(self.inner.clone(), R::operation_name(), request)
|
93 |
.await
|
94 |
}
|
95 |
}
|
96 |
|