ih/err/json.rs
1use std::{borrow::Borrow, fmt};
2
3use pb_jelly::Message;
4use sonic_rs::{Serialize, to_string};
5
6use crate::{Code, CodeBody, Json, State};
7
8impl fmt::Display for Json {
9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10 writeln!(f, "Json {}", self.inner)?;
11 Ok(())
12 }
13}
14
15pub fn json() -> Json {
16 Default::default()
17}
18
19impl std::error::Error for Json {}
20
21impl Json {
22 pub fn set<V: Serialize>(&mut self, key: impl AsRef<str>, val: impl Borrow<V>) {
23 if let Ok(key) = xerr::ok!(to_string(key.as_ref())) {
24 if let Ok(val) = xerr::ok!(to_string(val.borrow())) {
25 let inner = &mut self.inner;
26 inner.push(if inner.is_empty() { '{' } else { ',' });
27 self.inner += &key;
28 self.inner.push(':');
29 self.inner += &val;
30 }
31 }
32 }
33
34 pub fn throw(&mut self) -> anyhow::Result<()> {
35 if self.inner.is_empty() {
36 return Ok(());
37 }
38 let mut err = Json {
39 inner: std::mem::take(&mut self.inner),
40 };
41 err.inner.push('}');
42 Err(err.into())
43 }
44}
45
46// impl<K: AsRef<str>, V: Serialize> FnMut<(K, V)> for Json {
47// extern "rust-call" fn call_mut(&mut self, args: (K, V)) -> Self::Output {
48// self.set(args.0, args.1);
49// }
50// }
51//
52// impl<K: AsRef<str>, V: Serialize> FnOnce<(K, V)> for Json {
53// type Output = ();
54// extern "rust-call" fn call_once(self, _args: (K, V)) -> Self::Output {
55// unimplemented!()
56// }
57// }
58//
59//
60// impl FnMut<()> for Json {
61// extern "rust-call" fn call_mut(&mut self, args: ()) -> Self::Output {
62// if self.inner.is_empty() {
63// return Ok(());
64// }
65// let mut err = Json {
66// inner: std::mem::take(&mut self.inner),
67// };
68// err.inner.push('}');
69// Err(err.into())
70// }
71// }
72//
73// impl FnOnce<()> for Json {
74// type Output = anyhow::Result<()>;
75// extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
76// unimplemented!()
77// }
78// }