Debian Codegraph @

third_party/rust/glean-core/src/traits/object.rs

raw
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5 use std::fmt::Display;
6
7 use serde::{Deserialize, Serialize};
8 use serde_json::Value as JsonValue;
9
10 /// This type represents all possible errors that can occur when serializing or deserializing an object from/to JSON.
11 #[derive(Debug)]
12 pub struct ObjectError(serde_json::Error);
13
14 impl Display for ObjectError {
15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 Display::fmt(&self.0, f)
17 }
18 }
19
20 impl std::error::Error for ObjectError {}
21
22 /// An object that can be serialized into JSON.
23 ///
24 /// Objects are defined by their structure in the metrics definition.
25 ///
26 /// This is essentially a wrapper around serde's `Serialize`/`Deserialize`,
27 /// but in a way we can name it for our JSON (de)serialization.
28 pub trait ObjectSerialize {
29 /// Deserialize the object from its JSON representation.
30 ///
31 /// Returns an error if deserialization fails.
32 /// This should not happen for glean_parser-generated and later serialized objects.
33 fn from_str(obj: &str) -> Result<Self, ObjectError>
34 where
35 Self: Sized;
36
37 /// Serialize this object into a JSON string.
38 fn into_serialized_object(self) -> Result<JsonValue, ObjectError>;
39 }
40
41 impl<V> ObjectSerialize for V
42 where
43 V: Serialize,
44 V: for<'de> Deserialize<'de>,
45 {
46 fn from_str(obj: &str) -> Result<Self, ObjectError> {
47 serde_json::from_str(obj).map_err(ObjectError)
48 }
49
50 fn into_serialized_object(self) -> Result<JsonValue, ObjectError> {
51 serde_json::to_value(self).map_err(ObjectError)
52 }
53 }