mz_repr/explain/
json.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Structs and traits for `EXPLAIN AS JSON`.
11
12use crate::explain::*;
13
14/// A trait implemented by explanation types that can be rendered as
15/// [`ExplainFormat::Json`].
16pub trait DisplayJson
17where
18    Self: Sized,
19{
20    fn to_serde_value(&self) -> serde_json::Result<serde_json::Value>;
21}
22
23/// Render a type `t: T` as [`ExplainFormat::Json`].
24///
25/// # Panics
26///
27/// Panics if the [`DisplayJson::to_serde_value`] or the subsequent
28/// [`serde_json::to_string_pretty`] call return a [`serde_json::Error`].
29pub fn json_string<T: DisplayJson>(t: &T) -> String {
30    let value = t.to_serde_value().expect("serde_json::Value");
31    serde_json::to_string_pretty(&value).expect("JSON string")
32}
33
34impl DisplayJson for serde_json::Value {
35    fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
36        Ok(self.to_owned())
37    }
38}
39
40impl DisplayJson for String {
41    fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
42        Ok(serde_json::Value::String(self.clone()))
43    }
44}
45
46impl DisplayJson for UnsupportedFormat {
47    fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
48        unreachable!()
49    }
50}