diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 01:13:27 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 01:13:27 +0000 |
commit | 40a355a42d4a9444dc753c04c6608dade2f06a23 (patch) | |
tree | 871fc667d2de662f171103ce5ec067014ef85e61 /third_party/rust/glean-core/src/traits/object.rs | |
parent | Adding upstream version 124.0.1. (diff) | |
download | firefox-40a355a42d4a9444dc753c04c6608dade2f06a23.tar.xz firefox-40a355a42d4a9444dc753c04c6608dade2f06a23.zip |
Adding upstream version 125.0.1.upstream/125.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/glean-core/src/traits/object.rs')
-rw-r--r-- | third_party/rust/glean-core/src/traits/object.rs | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/third_party/rust/glean-core/src/traits/object.rs b/third_party/rust/glean-core/src/traits/object.rs new file mode 100644 index 0000000000..c579efeac7 --- /dev/null +++ b/third_party/rust/glean-core/src/traits/object.rs @@ -0,0 +1,53 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +use std::fmt::Display; + +use serde::{Deserialize, Serialize}; +use serde_json::Value as JsonValue; + +/// This type represents all possible errors that can occur when serializing or deserializing an object from/to JSON. +#[derive(Debug)] +pub struct ObjectError(serde_json::Error); + +impl Display for ObjectError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + Display::fmt(&self.0, f) + } +} + +impl std::error::Error for ObjectError {} + +/// An object that can be serialized into JSON. +/// +/// Objects are defined by their structure in the metrics definition. +/// +/// This is essentially a wrapper around serde's `Serialize`/`Deserialize`, +/// but in a way we can name it for our JSON (de)serialization. +pub trait ObjectSerialize { + /// Deserialize the object from its JSON representation. + /// + /// Returns an error if deserialization fails. + /// This should not happen for glean_parser-generated and later serialized objects. + fn from_str(obj: &str) -> Result<Self, ObjectError> + where + Self: Sized; + + /// Serialize this object into a JSON string. + fn into_serialized_object(self) -> Result<JsonValue, ObjectError>; +} + +impl<V> ObjectSerialize for V +where + V: Serialize, + V: for<'de> Deserialize<'de>, +{ + fn from_str(obj: &str) -> Result<Self, ObjectError> { + serde_json::from_str(obj).map_err(ObjectError) + } + + fn into_serialized_object(self) -> Result<JsonValue, ObjectError> { + serde_json::to_value(self).map_err(ObjectError) + } +} |