spectrusty_core/bus/dynbus/
serde.rs

1/*
2    Copyright (C) 2020-2022  Rafal Michalski
3
4    This file is part of SPECTRUSTY, a Rust library for building emulators.
5
6    For the full copyright notice, see the lib.rs file.
7*/
8#![allow(clippy::borrowed_box)]
9use core::fmt::{self, Debug};
10use core::ops::{Deref, DerefMut};
11use core::marker::PhantomData;
12use ::serde::{
13    Serialize, Serializer, Deserialize, Deserializer,
14    ser::{SerializeStruct, SerializeSeq},
15    de::{self, Visitor, SeqAccess, MapAccess}
16};
17use crate::clock::TimestampOps;
18use super::*;
19use super::super::{VFNullDevice, BusDevice};
20
21/// This trait needs to be implemented by a type provided to [DynamicSerdeBus] as a parameter `S`,
22/// to serialize dynamic devices.
23pub trait SerializeDynDevice {
24    /// This function should serialize the provided dynamic device.
25    ///
26    /// The serialized form of the `device` depends completely on the implementation of this function,
27    /// however it should probably include some device identifier along with the device data.
28    fn serialize_dyn_device<T: TimestampOps + Serialize + 'static,
29                            S: Serializer>(
30        device: &Box<dyn NamedBusDevice<T>>,
31        serializer: S
32    ) -> Result<S::Ok, S::Error>;
33}
34
35/// This trait needs to be implemented by a type provided to [DynamicSerdeBus] as a parameter `S`,
36/// to deserialize dynamic devices.
37pub trait DeserializeDynDevice<'de> {
38    /// This function should deserialize and return the dynamic device on success.
39    fn deserialize_dyn_device<T: Default + TimestampOps + Deserialize<'de> + 'static,
40                              D: Deserializer<'de>>(
41        deserializer: D
42    ) -> Result<Box<dyn NamedBusDevice<T>>, D::Error>;
43}
44
45/// A terminated [DynamicSerdeBus] pseudo-device with [`VFNullDevice<V>`][VFNullDevice].
46pub type DynamicSerdeVBus<S, V> = DynamicSerdeBus<S, VFNullDevice<V>>;
47
48/// A wrapper for [DynamicBus] that is able to serialize and deserialize together with currently
49/// attached dynamic devices.
50///
51/// Use this type instead of [DynamicBus] when specifying [crate::chip::ControlUnit::BusDevice] or
52/// [BusDevice::NextDevice].
53///
54/// A type that implements [SerializeDynDevice] and [DeserializeDynDevice] must be declared as
55/// generic parameter `S`.
56#[repr(transparent)]
57pub struct DynamicSerdeBus<S, D: BusDevice>(DynamicBus<D>, PhantomData<S>);
58
59impl<SDD, B> Serialize for DynamicSerdeBus<SDD, B>
60    where SDD: SerializeDynDevice,
61          B: BusDevice + Serialize,
62          B::Timestamp: TimestampOps + Serialize + 'static
63{
64    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
65
66        struct DevWrap<'a, T, SDD>(
67            &'a Box<dyn NamedBusDevice<T>>, PhantomData<SDD>
68        );
69
70        impl<'a, T, SDD> Serialize for DevWrap<'a, T, SDD>
71            where T: TimestampOps + Serialize + 'static,
72                  SDD: SerializeDynDevice
73        {
74            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75                SDD::serialize_dyn_device(self.0, serializer)
76            }
77        }
78
79        struct SliceDevWrap<'a, T, SDD>(&'a [BoxNamedDynDevice<T>], PhantomData<SDD>);
80
81        impl<'a, T, SDD> Serialize for SliceDevWrap<'a, T, SDD>
82            where T: TimestampOps + Serialize + 'static,
83                  SDD: SerializeDynDevice
84        {
85            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
86                let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
87                for device in self.0 {
88                    seq.serialize_element(&DevWrap::<T, SDD>(device, PhantomData))?;
89                }
90                seq.end()
91            }
92        }
93
94        let mut state = serializer.serialize_struct("DynamicBus", 2)?;
95        state.serialize_field("bus", &self.0.bus)?;
96        let devices = SliceDevWrap::<B::Timestamp, SDD>(&self.0.devices, PhantomData);
97        state.serialize_field("devices", &devices)?;
98        state.end()
99    }
100}
101
102impl<'de, DDD, B> Deserialize<'de> for DynamicSerdeBus<DDD, B>
103    where DDD: DeserializeDynDevice<'de> + 'de,
104          B: BusDevice + Deserialize<'de> + Default,
105          B::Timestamp: Default + TimestampOps + Deserialize<'de> + 'static
106{
107    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
108
109        struct BoxedDevWrap<'de, T, DDD>(
110            BoxNamedDynDevice<T>, PhantomData<&'de DDD>
111        );
112
113        impl<'de, T, DDD> Deserialize<'de> for BoxedDevWrap<'de, T, DDD>
114            where T: Default + TimestampOps + Deserialize<'de> + 'static,
115                  DDD: DeserializeDynDevice<'de>
116        {
117            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118                Ok(BoxedDevWrap(DDD::deserialize_dyn_device(deserializer)?, PhantomData))
119            }
120        }
121
122        struct DevicesWrap<'de, T, DDD>(
123            Vec<BoxNamedDynDevice<T>>, PhantomData<&'de DDD>
124        );
125
126        impl<'de, T, DDD> Deserialize<'de> for DevicesWrap<'de, T, DDD>
127            where T: Default + TimestampOps + Deserialize<'de> + 'static,
128                  DDD: DeserializeDynDevice<'de>
129        {
130            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
131
132                struct SeqDevVisitor<T, DDD>(PhantomData<T>, PhantomData<DDD>);
133
134                impl<'de, T, DDD> Visitor<'de> for SeqDevVisitor<T, DDD>
135                    where T: Default + TimestampOps + Deserialize<'de> + 'static,
136                          DDD: DeserializeDynDevice<'de> + 'de
137                {
138                    type Value = DevicesWrap<'de, T, DDD>;
139
140                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
141                        formatter.write_str("a sequence of dynamic bus devices")
142                    }
143
144                    fn visit_seq<V: SeqAccess<'de>>(self, mut seq: V) -> Result<Self::Value, V::Error> {
145                        let mut vec = Vec::new();
146                        if let Some(size) = seq.size_hint() {
147                            vec.reserve_exact(size);
148                        }
149                        while let Some(BoxedDevWrap::<T, DDD>(dev, ..)) = seq.next_element()? {
150                            vec.push(dev);
151                        }
152                        Ok(DevicesWrap(vec, PhantomData))
153                    }
154                }
155
156                deserializer.deserialize_seq(SeqDevVisitor::<T, DDD>(PhantomData, PhantomData))
157            }
158        }
159
160        #[derive(Deserialize)]
161        #[serde(field_identifier, rename_all = "lowercase")]
162        enum Field { Bus, Devices }
163
164        struct DynamicBusVisitor<DDD, B>(PhantomData<DDD>, PhantomData<B>);
165
166        impl<'de, DDD, B> Visitor<'de> for DynamicBusVisitor<DDD, B>
167            where DDD: DeserializeDynDevice<'de> + 'de,
168                  B: BusDevice + Deserialize<'de> + Default,
169                  B::Timestamp: Default + TimestampOps + Deserialize<'de> + 'static
170        {
171            type Value = DynamicSerdeBus<DDD, B>;
172
173            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
174                formatter.write_str("struct DynamicBus")
175            }
176
177            fn visit_seq<V: SeqAccess<'de>>(self, mut seq: V) -> Result<Self::Value, V::Error> {
178                let bus = seq.next_element()?.unwrap_or_default();
179                let DevicesWrap::<B::Timestamp, DDD>(devices, ..) = seq.next_element()?
180                                .unwrap_or_else(|| DevicesWrap(Vec::new(), PhantomData));
181                Ok(DynamicSerdeBus(DynamicBus { devices, bus }, PhantomData))
182            }
183
184            fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {
185                let mut devices = Vec::new();
186                let mut bus = None;
187                while let Some(key) = map.next_key()? {
188                    match key {
189                        Field::Bus => {
190                            if bus.is_some() {
191                                return Err(de::Error::duplicate_field("bus"));
192                            }
193                            bus = Some(map.next_value()?);
194                        }
195                        Field::Devices => {
196                            if !devices.is_empty() {
197                                return Err(de::Error::duplicate_field("devices"));
198                            }
199                            devices = map.next_value::<DevicesWrap<B::Timestamp, DDD>>()?.0;
200                        }
201                    }
202                }
203                let bus = bus.unwrap_or_default();
204                Ok(DynamicSerdeBus(DynamicBus { devices, bus }, PhantomData))
205            }
206        }
207
208        const FIELDS: &[&str] = &["bus", "devices"];
209        deserializer.deserialize_struct("DynamicBus", FIELDS,
210                     DynamicBusVisitor::<DDD, B>(PhantomData, PhantomData))
211    }
212}
213
214impl<S, D> Default for DynamicSerdeBus<S, D>
215    where D: BusDevice + Default,
216          D::Timestamp: Default
217{
218    fn default() -> Self {
219        DynamicSerdeBus(DynamicBus::default(), PhantomData)
220    }
221}
222
223impl<S, D> fmt::Debug for DynamicSerdeBus<S, D>
224    where D: BusDevice + fmt::Debug,
225          D::Timestamp: fmt::Debug
226{
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        self.0.fmt(f)
229    }
230}
231
232impl<S, D: BusDevice> Deref for DynamicSerdeBus<S, D> {
233    type Target = DynamicBus<D>;
234
235    fn deref(&self) -> &Self::Target {
236        &self.0
237    }
238}
239
240impl<S, D: BusDevice> DerefMut for DynamicSerdeBus<S, D> {
241    fn deref_mut(&mut self) -> &mut Self::Target {
242        &mut self.0
243    }
244}
245
246impl<S, D: BusDevice> From<DynamicBus<D>> for DynamicSerdeBus<S, D> {
247    fn from(dynamic_bus: DynamicBus<D>) -> Self {
248        DynamicSerdeBus(dynamic_bus, PhantomData)
249    }
250}
251
252impl<S, D: BusDevice> From<DynamicSerdeBus<S, D>> for DynamicBus<D> {
253    fn from(dynamic_bus: DynamicSerdeBus<S, D>) -> Self {
254        dynamic_bus.0
255    }
256}
257
258impl<S, D: BusDevice> BusDevice for DynamicSerdeBus<S, D>
259    where D: BusDevice,
260          D::Timestamp: Copy + Debug
261{
262    type Timestamp = D::Timestamp;
263    type NextDevice = D;
264
265    #[inline(always)]
266    fn next_device_mut(&mut self) -> &mut Self::NextDevice {
267        self.0.next_device_mut()
268    }
269    #[inline(always)]
270    fn next_device_ref(&self) -> &Self::NextDevice {
271        self.0.next_device_ref()
272    }
273    #[inline(always)]
274    fn into_next_device(self) -> Self::NextDevice {
275        self.0.into_next_device()
276    }
277    #[inline(always)]
278    fn reset(&mut self, timestamp: Self::Timestamp) {
279        self.0.reset(timestamp)
280    }
281    #[inline(always)]
282    fn update_timestamp(&mut self, timestamp: Self::Timestamp) {
283        self.0.update_timestamp(timestamp)
284    }
285    #[inline(always)]
286    fn next_frame(&mut self, timestamp: Self::Timestamp) {
287        self.0.next_frame(timestamp)
288    }
289    #[inline(always)]
290    fn read_io(&mut self, port: u16, timestamp: Self::Timestamp) -> Option<(u8, Option<NonZeroU16>)> {
291        self.0.read_io(port, timestamp)
292    }
293    #[inline(always)]
294    fn write_io(&mut self, port: u16, data: u8, timestamp: Self::Timestamp) -> Option<u16> {
295        self.0.write_io(port, data, timestamp)
296    }
297}