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.
910//! Structs and traits for `EXPLAIN AS JSON`.
1112use crate::explain::*;
1314/// A trait implemented by explanation types that can be rendered as
15/// [`ExplainFormat::Json`].
16pub trait DisplayJson
17where
18Self: Sized,
19{
20fn to_serde_value(&self) -> serde_json::Result<serde_json::Value>;
21}
2223/// 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 {
30let value = t.to_serde_value().expect("serde_json::Value");
31 serde_json::to_string_pretty(&value).expect("JSON string")
32}
3334impl DisplayJson for serde_json::Value {
35fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
36Ok(self.to_owned())
37 }
38}
3940impl DisplayJson for String {
41fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
42Ok(serde_json::Value::String(self.clone()))
43 }
44}
4546impl DisplayJson for UnsupportedFormat {
47fn to_serde_value(&self) -> serde_json::Result<serde_json::Value> {
48unreachable!()
49 }
50}