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