kernel_sidecar/jupyter/iopub_content/
display_data.rs

1/*
2https://jupyter-client.readthedocs.io/en/latest/messaging.html#display-data
3*/
4use std::collections::HashMap;
5
6use bytes::Bytes;
7use serde::{Deserialize, Deserializer, Serialize};
8
9#[derive(Clone, Deserialize, Debug, Serialize, PartialEq)]
10pub struct Transient {
11    pub display_id: String,
12}
13
14// If the transient field is an empty dict, deserialize it as None
15// otherwise deserialize it as Some(Transient)
16fn deserialize_transient<'de, D>(deserializer: D) -> Result<Option<Transient>, D::Error>
17where
18    D: Deserializer<'de>,
19{
20    let v: Option<serde_json::Value> = Option::deserialize(deserializer)?;
21    match v {
22        Some(serde_json::Value::Object(map)) if map.is_empty() => Ok(None),
23        Some(value) => serde_json::from_value(value)
24            .map(Some)
25            .map_err(serde::de::Error::custom),
26        None => Ok(None),
27    }
28}
29
30#[derive(Clone, Deserialize, Debug, Serialize, PartialEq)]
31pub struct DisplayData {
32    pub data: HashMap<String, serde_json::Value>,
33    pub metadata: serde_json::Value,
34    // Dev note: serde(default) is important here, when using custom deserialize_with and Option
35    // then it will throw errors when the field is missing unless default is included.
36    #[serde(default, deserialize_with = "deserialize_transient")]
37    pub transient: Option<Transient>,
38}
39
40impl From<Bytes> for DisplayData {
41    fn from(bytes: Bytes) -> Self {
42        dbg!(&bytes);
43        serde_json::from_slice(&bytes).expect("Failed to deserialize DisplayData")
44    }
45}
46
47#[derive(Deserialize, Debug)]
48pub struct UpdateDisplayData {
49    pub data: HashMap<String, serde_json::Value>,
50    pub metadata: serde_json::Value,
51    // Dev note: serde(default) is important here, when using custom deserialize_with and Option
52    // then it will throw errors when the field is missing unless default is included.
53    #[serde(default, deserialize_with = "deserialize_transient")]
54    pub transient: Option<Transient>,
55}
56
57impl From<Bytes> for UpdateDisplayData {
58    fn from(bytes: Bytes) -> Self {
59        serde_json::from_slice(&bytes).expect("Failed to deserialize UpdateDisplayData")
60    }
61}