Skip to main content

agent_client_protocol_schema/
serde_util.rs

1//! Custom payload adapters, option-like field wrappers, and builder helpers for serde.
2//!
3//! ## Payload adapters
4//!
5//! - [`default_on_null`]: opt a defaultable payload into accepting null.
6//!
7//! ## Types
8//!
9//! - [`MaybeUndefined<T>`]: three-state: undefined (key absent), null, or value.
10//!
11//! ## Builder traits
12//!
13//! - [`IntoOption<T>`]: ergonomic conversion into `Option<T>` for builder methods.
14//! - [`IntoMaybeUndefined<T>`]: ergonomic conversion into `MaybeUndefined<T>` for builder methods.
15//!
16//! `MaybeUndefined` based on: <https://docs.rs/async-graphql/latest/src/async_graphql/types/maybe_undefined.rs.html>
17use std::{
18    borrow::Cow,
19    ffi::OsStr,
20    ops::Deref,
21    path::{Path, PathBuf},
22    sync::Arc,
23};
24
25use serde::{Deserialize, Deserializer, Serialize, Serializer};
26use serde_with::{DeserializeAs, de::DeserializeAsWrap};
27
28// ---- Default-on-null payloads ----
29
30/// Declares a defaultable payload whose `Deserialize` accepts null.
31///
32/// Declare the normal derives except `Deserialize` inside this macro. A private
33/// wire type derives deserialization from the same fields and attributes, so
34/// there is no second field definition to maintain and no public helper methods.
35/// `DefaultOnNull` wraps only deserialization of the entire payload. Serialization
36/// and JSON Schema are still derived directly on the public type.
37///
38/// Opt in explicitly. Implementing `Default` alone does not change wire behavior.
39macro_rules! default_on_null {
40    // Copies one field from the wire struct, keeping only the field's `#[cfg]`
41    // attributes so feature-gated fields compile with the feature off.
42    (@assign $payload:ident $wire:ident $field:ident []) => {
43        $payload.$field = $wire.$field;
44    };
45    (@assign $payload:ident $wire:ident $field:ident [[cfg $($condition:tt)*] $($rest:tt)*]) => {
46        #[cfg $($condition)*]
47        {
48            $crate::serde_util::default_on_null!(@assign $payload $wire $field [$($rest)*]);
49        }
50    };
51    (@assign $payload:ident $wire:ident $field:ident [[$($other:tt)*] $($rest:tt)*]) => {
52        $crate::serde_util::default_on_null!(@assign $payload $wire $field [$($rest)*]);
53    };
54    (
55        $(#[$attribute:meta])*
56        $visibility:vis struct $payload:ident {
57            $(
58                $(#[$($field_attribute:tt)*])*
59                $field_visibility:vis $field:ident: $field_type:ty
60            ),* $(,)?
61        }
62    ) => {
63        $(#[$attribute])*
64        $visibility struct $payload {
65            $(
66                $(#[$($field_attribute)*])*
67                $field_visibility $field: $field_type,
68            )*
69        }
70
71        impl<'de> serde::Deserialize<'de> for $payload {
72            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
73                $(#[$attribute])*
74                #[derive(serde::Deserialize)]
75                struct Wire {
76                    $(
77                        $(#[$($field_attribute)*])*
78                        $field_visibility $field: $field_type,
79                    )*
80                }
81
82                struct NonNull;
83
84                impl<'de> serde_with::DeserializeAs<'de, $payload> for NonNull {
85                    fn deserialize_as<D: serde::Deserializer<'de>>(
86                        deserializer: D,
87                    ) -> Result<$payload, D::Error> {
88                        let wire = <Wire as serde::Deserialize>::deserialize(deserializer)?;
89                        let mut payload = <$payload as Default>::default();
90                        $(
91                            $crate::serde_util::default_on_null!(
92                                @assign payload wire $field [$([$($field_attribute)*])*]
93                            );
94                        )*
95                        Ok(payload)
96                    }
97                }
98
99                <serde_with::DefaultOnNull<NonNull> as serde_with::DeserializeAs<
100                    'de,
101                    Self,
102                >>::deserialize_as(deserializer)
103            }
104        }
105    };
106}
107
108pub(crate) use default_on_null;
109
110#[cfg(test)]
111mod default_on_null_tests {
112    use serde::{Deserialize, Serialize, de::DeserializeOwned};
113    use serde_json::{Value, json};
114
115    use crate::{
116        MaybeUndefined,
117        rpc::{JsonRpcMessage, Request, Response},
118        v1::{
119            self, LoadSessionResponse, NewSessionResponse, PromptResponse, ReadTextFileResponse,
120            RequestPermissionResponse, WaitForTerminalExitResponse, WriteTextFileResponse,
121        },
122    };
123
124    // Keep one inventory for the value, streaming, serialization, and schema checks.
125    // Feature gates match the payloads, so the inventory also runs without default
126    // features and with individual unstable features enabled.
127    macro_rules! for_each_defaultable_payload {
128        ($check:ident) => {
129            $check::<v1::AuthenticateResponse>();
130            $check::<v1::LogoutRequest>();
131            $check::<v1::LogoutResponse>();
132            $check::<v1::LoadSessionResponse>();
133            $check::<v1::ResumeSessionResponse>();
134            $check::<v1::CloseSessionResponse>();
135            $check::<v1::ListSessionsRequest>();
136            $check::<v1::DeleteSessionResponse>();
137            $check::<v1::SetSessionModeResponse>();
138            $check::<v1::WriteTextFileResponse>();
139            $check::<v1::ReleaseTerminalResponse>();
140            $check::<v1::KillTerminalResponse>();
141            $check::<v1::WaitForTerminalExitResponse>();
142
143            #[cfg(feature = "unstable_auth_status")]
144            $check::<v1::AuthStatusRequest>();
145
146            #[cfg(feature = "unstable_session_archive")]
147            {
148                $check::<v1::ArchiveSessionResponse>();
149                $check::<v1::UnarchiveSessionResponse>();
150            }
151
152            #[cfg(feature = "unstable_session_options")]
153            $check::<v1::SessionOptionsResponse>();
154
155            #[cfg(feature = "unstable_llm_providers")]
156            {
157                $check::<v1::ListProvidersRequest>();
158                $check::<v1::SetProviderResponse>();
159                $check::<v1::DisableProviderResponse>();
160            }
161
162            #[cfg(feature = "unstable_protocol_v2")]
163            {
164                use crate::v2;
165
166                $check::<v2::LoginAuthResponse>();
167                $check::<v2::LogoutAuthRequest>();
168                $check::<v2::LogoutAuthResponse>();
169                $check::<v2::ResumeSessionResponse>();
170                $check::<v2::CloseSessionResponse>();
171                $check::<v2::ListSessionsRequest>();
172                $check::<v2::DeleteSessionResponse>();
173                $check::<v2::CancelToolCallResponse>();
174                $check::<v2::CancelTerminalResponse>();
175
176                #[cfg(feature = "unstable_auth_status")]
177                $check::<v2::AuthStatusRequest>();
178
179                #[cfg(feature = "unstable_session_archive")]
180                {
181                    $check::<v2::ArchiveSessionResponse>();
182                    $check::<v2::UnarchiveSessionResponse>();
183                }
184
185                #[cfg(feature = "unstable_session_options")]
186                $check::<v2::SessionOptionsResponse>();
187
188                #[cfg(feature = "unstable_llm_providers")]
189                {
190                    $check::<v2::ListProvidersRequest>();
191                    $check::<v2::SetProviderResponse>();
192                    $check::<v2::DisableProviderResponse>();
193                }
194            }
195        };
196    }
197
198    fn assert_defaultable_payload<T>()
199    where
200        T: Default + DeserializeOwned + Serialize + PartialEq + std::fmt::Debug,
201    {
202        let name = std::any::type_name::<T>();
203        for value in [Value::Null, json!({})] {
204            assert_eq!(
205                serde_json::from_value::<T>(value).unwrap(),
206                T::default(),
207                "{name}",
208            );
209        }
210        assert_eq!(
211            serde_json::from_str::<T>("null").unwrap(),
212            T::default(),
213            "{name}",
214        );
215        assert_eq!(
216            serde_json::to_value(T::default()).unwrap(),
217            json!({}),
218            "{name}"
219        );
220
221        let metadata = json!({"_meta": {"example.com/key": ["preserve", 1, null]}});
222        let payload: T = serde_json::from_value(metadata.clone()).unwrap();
223        assert_eq!(serde_json::to_value(payload).unwrap(), metadata, "{name}");
224
225        for value in [json!(false), json!(42), json!("invalid")] {
226            assert!(serde_json::from_value::<T>(value).is_err(), "{name}");
227        }
228
229        // Opting in the payload must not swallow null in surrounding wrappers.
230        assert_eq!(
231            serde_json::from_value::<Option<T>>(Value::Null).unwrap(),
232            None,
233            "{name}",
234        );
235        assert_eq!(
236            serde_json::from_value::<MaybeUndefined<T>>(Value::Null).unwrap(),
237            MaybeUndefined::Null,
238            "{name}",
239        );
240    }
241
242    #[test]
243    fn defaultable_payloads_accept_null_without_losing_information() {
244        for_each_defaultable_payload!(assert_defaultable_payload);
245    }
246
247    #[test]
248    fn inherent_methods_do_not_bypass_null_handling() {
249        // These must resolve to the trait too, not a strict inherent helper.
250        assert_eq!(
251            WriteTextFileResponse::deserialize(Value::Null).unwrap(),
252            WriteTextFileResponse::default(),
253        );
254        assert_eq!(
255            LoadSessionResponse::deserialize(Value::Null).unwrap(),
256            LoadSessionResponse::default(),
257        );
258    }
259
260    #[test]
261    fn optional_payload_fields_are_preserved() {
262        let load = json!({
263            "modes": {
264                "currentModeId": "ask",
265                "availableModes": [{"id": "ask", "name": "Ask"}]
266            },
267            "configOptions": [],
268            "_meta": {"example.com/key": "value"}
269        });
270        let response: LoadSessionResponse = serde_json::from_value(load.clone()).unwrap();
271        assert_eq!(serde_json::to_value(response).unwrap(), load);
272
273        let list = json!({"cwd": "/workspace", "cursor": "next-page"});
274        let request: v1::ListSessionsRequest = serde_json::from_value(list.clone()).unwrap();
275        assert_eq!(serde_json::to_value(request).unwrap(), list);
276
277        #[cfg(feature = "unstable_protocol_v2")]
278        {
279            let request: crate::v2::ListSessionsRequest =
280                serde_json::from_value(list.clone()).unwrap();
281            assert_eq!(serde_json::to_value(request).unwrap(), list);
282        }
283    }
284
285    #[test]
286    fn default_terminal_exit_status_is_unknown_not_success() {
287        let response: WaitForTerminalExitResponse = serde_json::from_value(Value::Null).unwrap();
288        assert_eq!(response.exit_status.exit_code, None);
289        assert_eq!(response.exit_status.signal, None);
290        assert_eq!(response, WaitForTerminalExitResponse::default());
291
292        for value in [
293            json!({"exitCode": 0}),
294            json!({"exitCode": 17}),
295            json!({"signal": "SIGTERM"}),
296        ] {
297            let response: WaitForTerminalExitResponse =
298                serde_json::from_value(value.clone()).unwrap();
299            assert_eq!(serde_json::to_value(response).unwrap(), value);
300        }
301    }
302
303    #[test]
304    fn non_null_payloads_keep_the_derived_deserialization_behavior() {
305        // A default exists, but the field is still required in non-null input.
306        // DefaultOnNull must not become DefaultOnError.
307        super::default_on_null! {
308            #[derive(Default, Debug, Serialize, PartialEq)]
309            struct RequiredField {
310                count: u32,
311            }
312        }
313        #[derive(Deserialize)]
314        struct BaselineWrite {
315            #[serde(
316                default,
317                rename = "_meta",
318                with = "serde_with::As::<serde_with::DefaultOnError>"
319            )]
320            meta: Option<serde_json::Map<String, Value>>,
321        }
322
323        assert_eq!(
324            serde_json::from_value::<RequiredField>(Value::Null).unwrap(),
325            RequiredField::default(),
326        );
327        assert!(serde_json::from_value::<RequiredField>(json!({})).is_err());
328        assert!(serde_json::from_value::<RequiredField>(json!({"count": "invalid"})).is_err());
329
330        for value in [
331            json!({}),
332            json!({"_meta": {"example.com/key": true}}),
333            json!({"_meta": 42}),
334            json!({"modes": "invalid", "configOptions": "invalid"}),
335            json!([]),
336            json!([null]),
337            json!(false),
338            json!(42),
339            json!("invalid"),
340        ] {
341            assert_eq!(
342                serde_json::from_value::<WriteTextFileResponse>(value.clone())
343                    .map(|response| response.meta)
344                    .map_err(|_| ()),
345                serde_json::from_value::<BaselineWrite>(value)
346                    .map(|response| response.meta)
347                    .map_err(|_| ()),
348            );
349        }
350    }
351
352    #[test]
353    fn payloads_with_required_fields_still_reject_null() {
354        assert!(serde_json::from_value::<ReadTextFileResponse>(Value::Null).is_err());
355        assert!(serde_json::from_value::<RequestPermissionResponse>(Value::Null).is_err());
356        assert!(serde_json::from_value::<NewSessionResponse>(Value::Null).is_err());
357        assert!(serde_json::from_value::<PromptResponse>(Value::Null).is_err());
358        assert!(serde_json::from_value::<v1::InitializeResponse>(Value::Null).is_err());
359        assert!(serde_json::from_value::<v1::CreateTerminalResponse>(Value::Null).is_err());
360        assert!(serde_json::from_value::<v1::TerminalOutputResponse>(Value::Null).is_err());
361        assert!(serde_json::from_value::<v1::CreateElicitationResponse>(Value::Null).is_err());
362
363        #[cfg(feature = "unstable_protocol_v2")]
364        {
365            use crate::v2;
366
367            assert!(serde_json::from_value::<v2::InitializeResponse>(Value::Null).is_err());
368            assert!(serde_json::from_value::<v2::NewSessionResponse>(Value::Null).is_err());
369            assert!(serde_json::from_value::<v2::PromptResponse>(Value::Null).is_err());
370            assert!(serde_json::from_value::<v2::RequestPermissionResponse>(Value::Null).is_err());
371            assert!(serde_json::from_value::<v2::CreateElicitationResponse>(Value::Null).is_err());
372        }
373    }
374
375    #[test]
376    fn raw_response_nulls_are_not_rewritten() {
377        let extension: v1::ExtResponse = serde_json::from_value(Value::Null).unwrap();
378        assert_eq!(serde_json::to_value(extension).unwrap(), Value::Null);
379
380        #[cfg(feature = "unstable_mcp_over_acp")]
381        {
382            let mcp: v1::MessageMcpResponse =
383                serde_json::from_value(json!({"result": null})).unwrap();
384            assert_eq!(serde_json::to_value(mcp).unwrap(), json!({"result": null}));
385        }
386
387        #[cfg(feature = "unstable_protocol_v2")]
388        {
389            let extension: crate::v2::ExtResponse = serde_json::from_value(Value::Null).unwrap();
390            assert_eq!(serde_json::to_value(extension).unwrap(), Value::Null);
391
392            #[cfg(feature = "unstable_mcp_over_acp")]
393            {
394                let mcp: crate::v2::MessageMcpResponse =
395                    serde_json::from_value(json!({"result": null})).unwrap();
396                assert_eq!(serde_json::to_value(mcp).unwrap(), json!({"result": null}));
397            }
398        }
399    }
400
401    #[test]
402    fn optional_request_parameters_keep_their_existing_meaning() {
403        type LogoutRequest = Request<v1::LogoutRequest>;
404        for value in [
405            json!({"id": 1, "method": "logout"}),
406            json!({"id": 1, "method": "logout", "params": null}),
407        ] {
408            let request: LogoutRequest = serde_json::from_value(value).unwrap();
409            assert_eq!(request.params, None);
410        }
411        let request: LogoutRequest =
412            serde_json::from_value(json!({"id": 1, "method": "logout", "params": {}})).unwrap();
413        assert_eq!(request.params, Some(v1::LogoutRequest::default()));
414    }
415
416    #[test]
417    fn nullable_fields_keep_their_existing_meaning() {
418        #[derive(Debug, Deserialize, PartialEq)]
419        struct Container {
420            optional: Option<WriteTextFileResponse>,
421            #[serde(default)]
422            patch: MaybeUndefined<WriteTextFileResponse>,
423        }
424
425        assert_eq!(
426            serde_json::from_value::<Option<WriteTextFileResponse>>(Value::Null).unwrap(),
427            None,
428        );
429        assert_eq!(
430            serde_json::from_value::<MaybeUndefined<WriteTextFileResponse>>(Value::Null).unwrap(),
431            MaybeUndefined::Null,
432        );
433        assert_eq!(
434            serde_json::from_value::<Container>(json!({})).unwrap(),
435            Container {
436                optional: None,
437                patch: MaybeUndefined::Undefined,
438            },
439        );
440        assert_eq!(
441            serde_json::from_value::<Container>(json!({"optional": null, "patch": null})).unwrap(),
442            Container {
443                optional: None,
444                patch: MaybeUndefined::Null,
445            },
446        );
447        assert_eq!(
448            serde_json::from_value::<Container>(json!({"optional": {}, "patch": {}})).unwrap(),
449            Container {
450                optional: Some(WriteTextFileResponse::default()),
451                patch: MaybeUndefined::Value(WriteTextFileResponse::default()),
452            },
453        );
454    }
455
456    #[test]
457    fn response_result_is_required_even_when_its_payload_accepts_null() {
458        type WriteResponse = Response<WriteTextFileResponse, Value>;
459        let response: WriteResponse =
460            serde_json::from_value(json!({"id": 1, "result": null})).unwrap();
461        assert_eq!(
462            response,
463            Response::new(1, Ok(WriteTextFileResponse::default())),
464        );
465        assert!(serde_json::from_value::<WriteResponse>(json!({"id": 1})).is_err());
466        assert!(
467            serde_json::from_value::<JsonRpcMessage<WriteResponse>>(
468                json!({"jsonrpc": "2.0", "id": 1})
469            )
470            .is_err()
471        );
472
473        let error = json!({"code": -32603, "message": "Internal error"});
474        let response: JsonRpcMessage<WriteResponse> = serde_json::from_value(json!({
475            "jsonrpc": "2.0",
476            "id": 1,
477            "error": error.clone()
478        }))
479        .unwrap();
480        assert_eq!(response.into_inner(), Response::new(1, Err(error)));
481    }
482
483    #[cfg(feature = "schemars")]
484    #[test]
485    fn defaultable_payload_schemas_still_require_objects() {
486        fn assert_object_schema<T: schemars::JsonSchema>() {
487            let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap();
488            assert_eq!(schema["type"], "object");
489            assert!(schema.get("anyOf").is_none());
490        }
491        for_each_defaultable_payload!(assert_object_schema);
492    }
493}
494
495// ---- IntoOption ----
496
497/// Utility trait for builder methods for optional values.
498/// This allows the caller to either pass in the value itself without wrapping it in `Some`,
499/// or to just pass in an Option if that is what they have.
500pub trait IntoOption<T> {
501    /// Converts this value into an optional builder argument.
502    fn into_option(self) -> Option<T>;
503}
504
505impl<T> IntoOption<T> for Option<T> {
506    fn into_option(self) -> Option<T> {
507        self
508    }
509}
510
511impl<T> IntoOption<T> for T {
512    fn into_option(self) -> Option<T> {
513        Some(self)
514    }
515}
516
517impl IntoOption<String> for &str {
518    fn into_option(self) -> Option<String> {
519        Some(self.into())
520    }
521}
522
523impl IntoOption<String> for &mut str {
524    fn into_option(self) -> Option<String> {
525        Some(self.into())
526    }
527}
528
529impl IntoOption<String> for &String {
530    fn into_option(self) -> Option<String> {
531        Some(self.into())
532    }
533}
534
535impl IntoOption<String> for Box<str> {
536    fn into_option(self) -> Option<String> {
537        Some(self.into())
538    }
539}
540
541impl IntoOption<String> for Cow<'_, str> {
542    fn into_option(self) -> Option<String> {
543        Some(self.into())
544    }
545}
546
547impl IntoOption<String> for Arc<str> {
548    fn into_option(self) -> Option<String> {
549        Some(self.to_string())
550    }
551}
552
553impl<T: ?Sized + AsRef<OsStr>> IntoOption<PathBuf> for &T {
554    fn into_option(self) -> Option<PathBuf> {
555        Some(self.into())
556    }
557}
558
559impl IntoOption<PathBuf> for Box<Path> {
560    fn into_option(self) -> Option<PathBuf> {
561        Some(self.into())
562    }
563}
564
565impl IntoOption<PathBuf> for Cow<'_, Path> {
566    fn into_option(self) -> Option<PathBuf> {
567        Some(self.into())
568    }
569}
570
571impl IntoOption<serde_json::Value> for &str {
572    fn into_option(self) -> Option<serde_json::Value> {
573        Some(self.into())
574    }
575}
576
577impl IntoOption<serde_json::Value> for String {
578    fn into_option(self) -> Option<serde_json::Value> {
579        Some(self.into())
580    }
581}
582
583impl IntoOption<serde_json::Value> for Cow<'_, str> {
584    fn into_option(self) -> Option<serde_json::Value> {
585        Some(self.into())
586    }
587}
588
589// ---- MaybeUndefined ----
590
591/// Similar to `Option`, but it has three states, `undefined`, `null` and `x`.
592///
593/// When using with Serde, you will likely want to skip serialization of `undefined`
594/// and add a `default` for deserialization.
595///
596/// # Example
597///
598/// ```rust
599/// use agent_client_protocol_schema::MaybeUndefined;
600/// use serde::{Serialize, Deserialize};
601///
602/// #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
603/// struct A {
604///     #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
605///     a: MaybeUndefined<i32>,
606/// }
607/// ```
608#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
609#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
610#[cfg_attr(feature = "schemars", schemars(with = "Option<Option<T>>", inline))]
611#[expect(
612    clippy::exhaustive_enums,
613    reason = "a JSON field is absent, null, or set"
614)]
615pub enum MaybeUndefined<T> {
616    /// The field was not present.
617    #[default]
618    Undefined,
619    /// The field was present with a JSON `null` value.
620    Null,
621    /// The field was present with a non-null value.
622    Value(T),
623}
624
625impl<T> MaybeUndefined<T> {
626    /// Returns true if the `MaybeUndefined<T>` is undefined.
627    #[inline]
628    pub const fn is_undefined(&self) -> bool {
629        matches!(self, MaybeUndefined::Undefined)
630    }
631
632    /// Returns true if the `MaybeUndefined<T>` is null.
633    #[inline]
634    pub const fn is_null(&self) -> bool {
635        matches!(self, MaybeUndefined::Null)
636    }
637
638    /// Returns true if the `MaybeUndefined<T>` contains value.
639    #[inline]
640    pub const fn is_value(&self) -> bool {
641        matches!(self, MaybeUndefined::Value(_))
642    }
643
644    /// Borrow the value, returns `None` if the `MaybeUndefined<T>` is
645    /// `undefined` or `null`, otherwise returns `Some(T)`.
646    #[inline]
647    pub const fn value(&self) -> Option<&T> {
648        match self {
649            MaybeUndefined::Value(value) => Some(value),
650            _ => None,
651        }
652    }
653
654    /// Converts the `MaybeUndefined<T>` to `Option<T>`.
655    #[inline]
656    pub fn take(self) -> Option<T> {
657        match self {
658            MaybeUndefined::Value(value) => Some(value),
659            _ => None,
660        }
661    }
662
663    /// Converts the `MaybeUndefined<T>` to `Option<Option<T>>`.
664    #[inline]
665    pub const fn as_opt_ref(&self) -> Option<Option<&T>> {
666        match self {
667            MaybeUndefined::Undefined => None,
668            MaybeUndefined::Null => Some(None),
669            MaybeUndefined::Value(value) => Some(Some(value)),
670        }
671    }
672
673    /// Converts the `MaybeUndefined<T>` to `Option<Option<&U>>`.
674    #[inline]
675    pub fn as_opt_deref<U>(&self) -> Option<Option<&U>>
676    where
677        U: ?Sized,
678        T: Deref<Target = U>,
679    {
680        match self {
681            MaybeUndefined::Undefined => None,
682            MaybeUndefined::Null => Some(None),
683            MaybeUndefined::Value(value) => Some(Some(&**value)),
684        }
685    }
686
687    /// Returns `true` if the `MaybeUndefined<T>` contains the given value.
688    #[inline]
689    pub fn contains_value<U>(&self, x: &U) -> bool
690    where
691        U: PartialEq<T>,
692    {
693        match self {
694            MaybeUndefined::Value(y) => x == y,
695            _ => false,
696        }
697    }
698
699    /// Returns `true` if the `MaybeUndefined<T>` contains the given nullable
700    /// value.
701    #[inline]
702    pub fn contains<U>(&self, x: Option<&U>) -> bool
703    where
704        U: PartialEq<T>,
705    {
706        match self {
707            MaybeUndefined::Value(y) => matches!(x, Some(v) if v == y),
708            MaybeUndefined::Null => x.is_none(),
709            MaybeUndefined::Undefined => false,
710        }
711    }
712
713    /// Maps a `MaybeUndefined<T>` to `MaybeUndefined<U>` by applying a function
714    /// to the contained nullable value
715    #[inline]
716    pub fn map<U, F: FnOnce(Option<T>) -> Option<U>>(self, f: F) -> MaybeUndefined<U> {
717        match self {
718            MaybeUndefined::Value(v) => match f(Some(v)) {
719                Some(v) => MaybeUndefined::Value(v),
720                None => MaybeUndefined::Null,
721            },
722            MaybeUndefined::Null => match f(None) {
723                Some(v) => MaybeUndefined::Value(v),
724                None => MaybeUndefined::Null,
725            },
726            MaybeUndefined::Undefined => MaybeUndefined::Undefined,
727        }
728    }
729
730    /// Maps a `MaybeUndefined<T>` to `MaybeUndefined<U>` by applying a function
731    /// to the contained value
732    #[inline]
733    pub fn map_value<U, F: FnOnce(T) -> U>(self, f: F) -> MaybeUndefined<U> {
734        match self {
735            MaybeUndefined::Value(v) => MaybeUndefined::Value(f(v)),
736            MaybeUndefined::Null => MaybeUndefined::Null,
737            MaybeUndefined::Undefined => MaybeUndefined::Undefined,
738        }
739    }
740
741    /// Update `value` if the `MaybeUndefined<T>` is not undefined.
742    ///
743    /// # Example
744    ///
745    /// ```rust
746    /// use agent_client_protocol_schema::MaybeUndefined;
747    ///
748    /// let mut value = None;
749    ///
750    /// MaybeUndefined::Value(10i32).update_to(&mut value);
751    /// assert_eq!(value, Some(10));
752    ///
753    /// MaybeUndefined::Undefined.update_to(&mut value);
754    /// assert_eq!(value, Some(10));
755    ///
756    /// MaybeUndefined::Null.update_to(&mut value);
757    /// assert_eq!(value, None);
758    /// ```
759    pub fn update_to(self, value: &mut Option<T>) {
760        match self {
761            MaybeUndefined::Value(new) => *value = Some(new),
762            MaybeUndefined::Null => *value = None,
763            MaybeUndefined::Undefined => {}
764        }
765    }
766}
767
768impl<T, E> MaybeUndefined<Result<T, E>> {
769    /// Transposes a `MaybeUndefined` of a [`Result`] into a [`Result`] of a
770    /// `MaybeUndefined`.
771    ///
772    /// [`MaybeUndefined::Undefined`] will be mapped to
773    /// [`Ok`]`(`[`MaybeUndefined::Undefined`]`)`. [`MaybeUndefined::Null`]
774    /// will be mapped to [`Ok`]`(`[`MaybeUndefined::Null`]`)`.
775    /// [`MaybeUndefined::Value`]`(`[`Ok`]`(_))` and
776    /// [`MaybeUndefined::Value`]`(`[`Err`]`(_))` will be mapped to
777    /// [`Ok`]`(`[`MaybeUndefined::Value`]`(_))` and [`Err`]`(_)`.
778    ///
779    /// # Errors
780    ///
781    /// Returns an error if the input is [`MaybeUndefined::Value`]`(`[`Err`]`(_))`.
782    #[inline]
783    pub fn transpose(self) -> Result<MaybeUndefined<T>, E> {
784        match self {
785            MaybeUndefined::Undefined => Ok(MaybeUndefined::Undefined),
786            MaybeUndefined::Null => Ok(MaybeUndefined::Null),
787            MaybeUndefined::Value(Ok(v)) => Ok(MaybeUndefined::Value(v)),
788            MaybeUndefined::Value(Err(e)) => Err(e),
789        }
790    }
791}
792
793impl<T: Serialize> Serialize for MaybeUndefined<T> {
794    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
795        match self {
796            MaybeUndefined::Value(value) => value.serialize(serializer),
797            MaybeUndefined::Null => serializer.serialize_none(),
798            MaybeUndefined::Undefined => serializer.serialize_unit(),
799        }
800    }
801}
802
803impl<'de, T> Deserialize<'de> for MaybeUndefined<T>
804where
805    T: Deserialize<'de>,
806{
807    fn deserialize<D>(deserializer: D) -> Result<MaybeUndefined<T>, D::Error>
808    where
809        D: Deserializer<'de>,
810    {
811        Option::<T>::deserialize(deserializer).map(|value| match value {
812            Some(value) => MaybeUndefined::Value(value),
813            None => MaybeUndefined::Null,
814        })
815    }
816}
817
818impl<T> From<MaybeUndefined<T>> for Option<Option<T>> {
819    fn from(maybe_undefined: MaybeUndefined<T>) -> Self {
820        match maybe_undefined {
821            MaybeUndefined::Undefined => None,
822            MaybeUndefined::Null => Some(None),
823            MaybeUndefined::Value(value) => Some(Some(value)),
824        }
825    }
826}
827
828impl<T> From<Option<Option<T>>> for MaybeUndefined<T> {
829    fn from(value: Option<Option<T>>) -> Self {
830        match value {
831            Some(Some(value)) => Self::Value(value),
832            Some(None) => Self::Null,
833            None => Self::Undefined,
834        }
835    }
836}
837
838impl<'de, T, TAs> DeserializeAs<'de, MaybeUndefined<T>> for MaybeUndefined<TAs>
839where
840    TAs: DeserializeAs<'de, T>,
841{
842    fn deserialize_as<D>(deserializer: D) -> Result<MaybeUndefined<T>, D::Error>
843    where
844        D: Deserializer<'de>,
845    {
846        Option::<DeserializeAsWrap<T, TAs>>::deserialize(deserializer).map(|value| match value {
847            Some(value) => MaybeUndefined::Value(value.into_inner()),
848            None => MaybeUndefined::Null,
849        })
850    }
851}
852
853/// Utility trait for builder methods for optional values.
854/// This allows the caller to either pass in the value itself without wrapping it in `Some`,
855/// or to just pass in an Option if that is what they have, or set it back to undefined.
856pub trait IntoMaybeUndefined<T> {
857    /// Converts this value into a three-state builder argument.
858    fn into_maybe_undefined(self) -> MaybeUndefined<T>;
859}
860
861impl<T> IntoMaybeUndefined<T> for T {
862    fn into_maybe_undefined(self) -> MaybeUndefined<T> {
863        MaybeUndefined::Value(self)
864    }
865}
866
867impl<T> IntoMaybeUndefined<T> for Option<T> {
868    fn into_maybe_undefined(self) -> MaybeUndefined<T> {
869        match self {
870            Some(value) => MaybeUndefined::Value(value),
871            None => MaybeUndefined::Null,
872        }
873    }
874}
875
876impl<T> IntoMaybeUndefined<T> for MaybeUndefined<T> {
877    fn into_maybe_undefined(self) -> MaybeUndefined<T> {
878        self
879    }
880}
881
882impl IntoMaybeUndefined<String> for &str {
883    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
884        MaybeUndefined::Value(self.into())
885    }
886}
887
888impl IntoMaybeUndefined<String> for &mut str {
889    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
890        MaybeUndefined::Value(self.into())
891    }
892}
893
894impl IntoMaybeUndefined<String> for &String {
895    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
896        MaybeUndefined::Value(self.into())
897    }
898}
899
900impl IntoMaybeUndefined<String> for Box<str> {
901    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
902        MaybeUndefined::Value(self.into())
903    }
904}
905
906impl IntoMaybeUndefined<String> for Cow<'_, str> {
907    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
908        MaybeUndefined::Value(self.into())
909    }
910}
911
912impl IntoMaybeUndefined<String> for Arc<str> {
913    fn into_maybe_undefined(self) -> MaybeUndefined<String> {
914        MaybeUndefined::Value(self.to_string())
915    }
916}
917
918impl<T: ?Sized + AsRef<OsStr>> IntoMaybeUndefined<PathBuf> for &T {
919    fn into_maybe_undefined(self) -> MaybeUndefined<PathBuf> {
920        MaybeUndefined::Value(self.into())
921    }
922}
923
924impl IntoMaybeUndefined<PathBuf> for Box<Path> {
925    fn into_maybe_undefined(self) -> MaybeUndefined<PathBuf> {
926        MaybeUndefined::Value(self.into())
927    }
928}
929
930impl IntoMaybeUndefined<PathBuf> for Cow<'_, Path> {
931    fn into_maybe_undefined(self) -> MaybeUndefined<PathBuf> {
932        MaybeUndefined::Value(self.into())
933    }
934}
935
936impl IntoMaybeUndefined<serde_json::Value> for &str {
937    fn into_maybe_undefined(self) -> MaybeUndefined<serde_json::Value> {
938        MaybeUndefined::Value(self.into())
939    }
940}
941
942impl IntoMaybeUndefined<serde_json::Value> for String {
943    fn into_maybe_undefined(self) -> MaybeUndefined<serde_json::Value> {
944        MaybeUndefined::Value(self.into())
945    }
946}
947
948impl IntoMaybeUndefined<serde_json::Value> for Cow<'_, str> {
949    fn into_maybe_undefined(self) -> MaybeUndefined<serde_json::Value> {
950        MaybeUndefined::Value(self.into())
951    }
952}
953
954#[cfg(test)]
955mod tests {
956    use serde::{Deserialize, Serialize};
957    use serde_json::{from_value, json, to_value};
958
959    use super::*;
960
961    #[test]
962    fn test_maybe_undefined_serde() {
963        #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
964        struct A {
965            #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
966            a: MaybeUndefined<i32>,
967        }
968
969        assert_eq!(to_value(MaybeUndefined::Value(100i32)).unwrap(), json!(100));
970
971        assert_eq!(
972            from_value::<MaybeUndefined<i32>>(json!(100)).unwrap(),
973            MaybeUndefined::Value(100)
974        );
975        assert_eq!(
976            from_value::<MaybeUndefined<i32>>(json!(null)).unwrap(),
977            MaybeUndefined::Null
978        );
979
980        assert_eq!(
981            to_value(&A {
982                a: MaybeUndefined::Value(100i32)
983            })
984            .unwrap(),
985            json!({"a": 100})
986        );
987
988        assert_eq!(
989            to_value(&A {
990                a: MaybeUndefined::Null,
991            })
992            .unwrap(),
993            json!({ "a": null })
994        );
995
996        assert_eq!(
997            to_value(&A {
998                a: MaybeUndefined::Undefined,
999            })
1000            .unwrap(),
1001            json!({})
1002        );
1003
1004        assert_eq!(
1005            from_value::<A>(json!({"a": 100})).unwrap(),
1006            A {
1007                a: MaybeUndefined::Value(100i32)
1008            }
1009        );
1010
1011        assert_eq!(
1012            from_value::<A>(json!({ "a": null })).unwrap(),
1013            A {
1014                a: MaybeUndefined::Null
1015            }
1016        );
1017
1018        assert_eq!(
1019            from_value::<A>(json!({})).unwrap(),
1020            A {
1021                a: MaybeUndefined::Undefined
1022            }
1023        );
1024    }
1025
1026    #[test]
1027    fn test_maybe_undefined_to_nested_option() {
1028        assert_eq!(Option::<Option<i32>>::from(MaybeUndefined::Undefined), None);
1029
1030        assert_eq!(
1031            Option::<Option<i32>>::from(MaybeUndefined::Null),
1032            Some(None)
1033        );
1034
1035        assert_eq!(
1036            Option::<Option<i32>>::from(MaybeUndefined::Value(42)),
1037            Some(Some(42))
1038        );
1039    }
1040
1041    #[test]
1042    fn test_as_opt_ref() {
1043        let value = MaybeUndefined::<String>::Undefined;
1044        let r = value.as_opt_ref();
1045        assert_eq!(r, None);
1046
1047        let value = MaybeUndefined::<String>::Null;
1048        let r = value.as_opt_ref();
1049        assert_eq!(r, Some(None));
1050
1051        let value = MaybeUndefined::<String>::Value("abc".to_string());
1052        let r = value.as_opt_ref();
1053        assert_eq!(r, Some(Some(&"abc".to_string())));
1054    }
1055
1056    #[test]
1057    fn test_as_opt_deref() {
1058        let value = MaybeUndefined::<String>::Undefined;
1059        let r = value.as_opt_deref();
1060        assert_eq!(r, None);
1061
1062        let value = MaybeUndefined::<String>::Null;
1063        let r = value.as_opt_deref();
1064        assert_eq!(r, Some(None));
1065
1066        let value = MaybeUndefined::<String>::Value("abc".to_string());
1067        let r = value.as_opt_deref();
1068        assert_eq!(r, Some(Some("abc")));
1069    }
1070
1071    #[test]
1072    fn test_contains_value() {
1073        let test = "abc";
1074
1075        let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
1076        assert!(!value.contains_value(&test));
1077
1078        value = MaybeUndefined::Null;
1079        assert!(!value.contains_value(&test));
1080
1081        value = MaybeUndefined::Value("abc".to_string());
1082        assert!(value.contains_value(&test));
1083    }
1084
1085    #[test]
1086    fn test_contains() {
1087        let test = Some("abc");
1088        let none: Option<&str> = None;
1089
1090        let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
1091        assert!(!value.contains(test.as_ref()));
1092        assert!(!value.contains(none.as_ref()));
1093
1094        value = MaybeUndefined::Null;
1095        assert!(!value.contains(test.as_ref()));
1096        assert!(value.contains(none.as_ref()));
1097
1098        value = MaybeUndefined::Value("abc".to_string());
1099        assert!(value.contains(test.as_ref()));
1100        assert!(!value.contains(none.as_ref()));
1101    }
1102
1103    #[test]
1104    fn test_map_value() {
1105        let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
1106        assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Undefined);
1107
1108        value = MaybeUndefined::Null;
1109        assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Null);
1110
1111        value = MaybeUndefined::Value(5);
1112        assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Value(true));
1113    }
1114
1115    #[test]
1116    fn test_map() {
1117        let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
1118        assert_eq!(value.map(|v| Some(v.is_some())), MaybeUndefined::Undefined);
1119
1120        value = MaybeUndefined::Null;
1121        assert_eq!(
1122            value.map(|v| Some(v.is_some())),
1123            MaybeUndefined::Value(false)
1124        );
1125
1126        value = MaybeUndefined::Value(5);
1127        assert_eq!(
1128            value.map(|v| Some(v.is_some())),
1129            MaybeUndefined::Value(true)
1130        );
1131    }
1132
1133    #[test]
1134    fn test_transpose() {
1135        let mut value: MaybeUndefined<Result<i32, &'static str>> = MaybeUndefined::Undefined;
1136        assert_eq!(value.transpose(), Ok(MaybeUndefined::Undefined));
1137
1138        value = MaybeUndefined::Null;
1139        assert_eq!(value.transpose(), Ok(MaybeUndefined::Null));
1140
1141        value = MaybeUndefined::Value(Ok(5));
1142        assert_eq!(value.transpose(), Ok(MaybeUndefined::Value(5)));
1143
1144        value = MaybeUndefined::Value(Err("error"));
1145        assert_eq!(value.transpose(), Err("error"));
1146    }
1147}