1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//! Adapter for serde's DeserializeSeed trait.

use core::{marker::PhantomData, ops::ControlFlow};

use serde::{
    de::{DeserializeSeed, SeqAccess},
    forward_to_deserialize_any, Deserialize, Deserializer,
};

use crate::{
    any::static_wrapper::OwnedStatic,
    any_trait,
    protocol::{
        visitor::{Sequence, SequenceScope, Status, Value},
        AnyTraitObj, AnyTraitSendObj, AsyncEffect, ControlFlowFor, Effect, SyncEffect,
    },
    AsVisitor, Builder as _,
};

pub enum Error<T> {
    Pending(T),
    Incomplete,
    Custom,
}

#[cfg(feature = "std")]
impl<T> std::error::Error for Error<T> {}

impl<T> core::fmt::Debug for Error<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Pending(_) => write!(f, "Pending"),
            Self::Incomplete => write!(f, "Incomplete"),
            Self::Custom => write!(f, "Custom"),
        }
    }
}

pub struct Builder<'ctx, T: DeserializeSeed<'ctx>, E>(
    Result<T::Value, Error<T>>,
    PhantomData<fn() -> E>,
);

impl<'ctx, T: DeserializeSeed<'ctx>, E: Effect<'ctx>> crate::Builder<'ctx, E> for Builder<'ctx, T, E>
where
    Self: AsVisitor<'ctx, E>,
{
    type Error = Error<T>;

    type Value = T::Value;

    fn build(self) -> Result<Self::Value, Self::Error> {
        self.0
    }

    type Seed = T;

    fn from_seed(seed: Self::Seed) -> Self {
        Self(Err(Error::Pending(seed)), PhantomData)
    }
}

impl<'ctx, T: DeserializeSeed<'ctx>> AsVisitor<'ctx, SyncEffect> for Builder<'ctx, T, SyncEffect> {
    fn as_visitor(&mut self) -> crate::protocol::Visitor<'_, 'ctx, SyncEffect> {
        AnyTraitObj::from_obj(self)
    }
}

impl<'ctx, T: DeserializeSeed<'ctx> + Send> AsVisitor<'ctx, AsyncEffect>
    for Builder<'ctx, T, AsyncEffect>
where
    T::Value: Send,
{
    fn as_visitor(&mut self) -> crate::protocol::Visitor<'_, 'ctx, AsyncEffect> {
        AnyTraitSendObj::from_obj_send(self)
    }
}

any_trait! {
    impl['a, 'ctx, T: DeserializeSeed<'ctx>, E] Builder<'ctx, T, E> = [
        dyn Value<'ctx, OwnedStatic<bool>> + 'a,
        dyn Sequence<'ctx> + 'a,
    ]
}

enum InjectedValue<'a, 'ctx, T> {
    Bool(bool),
    Sequence(&'a mut dyn SequenceScope<'ctx>),
    Extra(PhantomData<T>),
}

impl<'ctx, T: DeserializeSeed<'ctx>, E> Value<'ctx, OwnedStatic<bool>> for Builder<'ctx, T, E> {
    #[inline]
    fn visit<'a>(&'a mut self, OwnedStatic(bool_value): OwnedStatic<bool>) -> ControlFlowFor<'a, 'ctx> where 'ctx: 'a {
        let pending = core::mem::replace(&mut self.0, Err(Error::Incomplete));
        let Err(Error::Pending(value)) = pending else {
            todo!()
        };

        self.0 = value.deserialize(InjectedValue::Bool(bool_value));

        if self.0.is_err() {
            ControlFlow::Break(())
        } else {
            ControlFlow::Continue(())
        }
    }
}

impl<'ctx, T: DeserializeSeed<'ctx>, E> Sequence<'ctx> for Builder<'ctx, T, E> {
    #[inline]
    fn visit<'a>(&'a mut self, scope: &'a mut dyn SequenceScope<'ctx>) -> ControlFlowFor<'a, 'ctx> where 'ctx: 'a {
        let pending = core::mem::replace(&mut self.0, Err(Error::Incomplete));
        let Err(Error::Pending(value)) = pending else {
            todo!()
        };

        self.0 = value.deserialize(InjectedValue::Sequence(scope));

        if self.0.is_err() {
            ControlFlow::Break(())
        } else {
            ControlFlow::Continue(())
        }
    }
}

impl<T> core::fmt::Display for Error<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl<T> serde::de::Error for Error<T> {
    fn custom<U>(_msg: U) -> Self
    where
        U: core::fmt::Display,
    {
        Error::Custom
    }
}

impl<'a, 'ctx, T> Deserializer<'ctx> for InjectedValue<'a, 'ctx, T> {
    type Error = Error<T>;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'ctx>,
    {
        match self {
            InjectedValue::Bool(value) => visitor.visit_bool(value),
            InjectedValue::Sequence(scope) => visitor.visit_seq(SequenceAccess(scope, PhantomData)),
            InjectedValue::Extra(_) => unreachable!(),
        }
    }

    forward_to_deserialize_any! {
        <W: Visitor<'ctx>>
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier ignored_any
    }
}

struct SequenceAccess<'a, 'ctx, T>(&'a mut dyn SequenceScope<'ctx>, PhantomData<T>);

impl<'a, 'ctx, T> SeqAccess<'ctx> for SequenceAccess<'a, 'ctx, T> {
    type Error = Error<T>;

    fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error>
    where
        U: serde::de::DeserializeSeed<'ctx>,
    {
        let mut builder = Builder::<_, SyncEffect>::from_seed(seed);
        match self.0.next(builder.as_visitor()) {
            ControlFlow::Continue(Status::Continue) => match builder.build() {
                Ok(value) => Ok(Some(value)),
                Err(error) => Err(Error::Incomplete),
            },
            ControlFlow::Continue(Status::Done) => Ok(None),
            ControlFlow::Break(()) => Err(Error::Incomplete), // use the one from builder
                                                              // if any.
        }
    }
}