use alloc::{string::String, vec::Vec};
use serde::{Deserialize, Serialize};
use crate::{cbor_bytes::CborBytes, schema_id::SchemaSource};
const DEFAULT_CONTENT_TYPE: &str = "application/cbor";
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IoSchema {
pub schema: SchemaSource,
pub content_type: String,
}
impl IoSchema {
pub fn new(schema: SchemaSource) -> Self {
Self {
schema,
content_type: DEFAULT_CONTENT_TYPE.to_owned(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OpExample {
pub title: String,
pub input_cbor: CborBytes,
pub output_cbor: Option<CborBytes>,
pub notes: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OpDescriptor {
pub name: String,
pub summary: Option<String>,
pub input: IoSchema,
pub output: IoSchema,
pub examples: Vec<OpExample>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cbor_bytes::CborBytes;
use crate::schema_id::SchemaSource;
use alloc::string::ToString;
#[test]
fn descriptor_serde_roundtrip() {
let schema = SchemaSource::InlineCbor(CborBytes::new(vec![0x01]));
let io = IoSchema {
schema,
content_type: "application/cbor".to_string(),
};
let descriptor = OpDescriptor {
name: "op".to_string(),
summary: Some("desc".to_string()),
input: io.clone(),
output: io,
examples: vec![],
};
let serialized = match serde_json::to_string(&descriptor) {
Ok(json) => json,
Err(err) => panic!("serialize failed: {err:?}"),
};
let roundtrip: OpDescriptor = match serde_json::from_str(&serialized) {
Ok(desc) => desc,
Err(err) => panic!("deserialize failed: {err:?}"),
};
assert_eq!(roundtrip.name, "op");
}
}