wick_interface_types/
field.rs1use serde::{Deserialize, Serialize};
2
3use crate::{is_false, Type};
4
5#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6#[non_exhaustive]
7pub struct Field {
8 pub name: String,
10
11 #[serde(rename = "type")]
13 #[cfg_attr(feature = "parser", serde(deserialize_with = "crate::types::deserialize_type"))]
14 #[cfg_attr(
15 feature = "yaml",
16 serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
17 )]
18 pub ty: Type,
19
20 #[cfg(feature = "value")]
22 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub default: Option<serde_json::Value>,
24
25 #[serde(default, skip_serializing_if = "is_false")]
27 pub required: bool,
28
29 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub description: Option<String>,
32}
33
34impl Field {
35 pub fn new<T: Into<String>>(name: T, ty: Type) -> Self {
36 Self::new_with_description(name, ty, None)
37 }
38
39 pub fn new_with_description<T: Into<String>>(name: T, ty: Type, desc: Option<String>) -> Self {
40 Self {
41 name: name.into(),
42 description: desc,
43 #[cfg(feature = "value")]
44 default: None,
45 required: !matches!(ty, Type::Optional { .. }),
46 ty,
47 }
48 }
49
50 #[must_use]
52 pub fn name(&self) -> &str {
53 &self.name
54 }
55
56 pub const fn ty(&self) -> &Type {
58 &self.ty
59 }
60
61 #[must_use]
63 pub fn description(&self) -> Option<&str> {
64 self.description.as_deref()
65 }
66
67 #[must_use]
69 #[cfg(feature = "value")]
70 pub const fn default(&self) -> Option<&serde_json::Value> {
71 self.default.as_ref()
72 }
73
74 #[must_use]
76 pub const fn required(&self) -> bool {
77 self.required
78 }
79
80 #[must_use]
82 #[cfg(feature = "value")]
83 pub fn with_value(self, value: impl Into<serde_json::Value>) -> FieldValue {
84 FieldValue::new(self, value.into())
85 }
86}
87
88impl std::fmt::Display for Field {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.write_str(&self.name)?;
91 f.write_str(": ")?;
92 self.ty.fmt(f)
93 }
94}
95
96#[cfg(feature = "value")]
98#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
99#[non_exhaustive]
100pub struct FieldValue {
101 pub field: Field,
103 pub value: serde_json::Value,
105}
106
107#[cfg(feature = "value")]
108impl FieldValue {
109 #[must_use]
111 pub const fn new(field: Field, value: serde_json::Value) -> Self {
112 Self { field, value }
113 }
114
115 #[must_use]
117 pub fn name(&self) -> &str {
118 &self.field.name
119 }
120
121 pub const fn signature(&self) -> &Type {
123 &self.field.ty
124 }
125
126 #[must_use]
128 pub const fn value(&self) -> &serde_json::Value {
129 &self.value
130 }
131}