1use alloc::borrow::Cow;
3use alloc::string::String;
4use core::fmt;
5
6use deser_core::State;
7use deser_core::de::{Deserialize, OwnedSink, Sink, SinkHandle, Slot, default_atom};
8use deser_core::ext::{ExtValue, Extension};
9use deser_core::ser::{Describe, Emit, Serialize};
10use deser_core::{Atom, ContainerShape, Error, Text};
11
12#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
33pub struct Global {
34 path: String,
36 split: usize,
38}
39
40impl Global {
41 pub fn new(module: &str, name: &str) -> Global {
43 let mut path = String::with_capacity(module.len() + name.len() + 1);
44 path.push_str(module);
45 path.push('.');
46 path.push_str(name);
47 Global {
48 path,
49 split: module.len(),
50 }
51 }
52
53 pub fn module(&self) -> &str {
55 &self.path[..self.split]
56 }
57
58 pub fn name(&self) -> &str {
62 &self.path[self.split + 1..]
63 }
64
65 pub fn path(&self) -> &str {
67 &self.path
68 }
69}
70
71impl fmt::Debug for Global {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "Global({})", self.path)
74 }
75}
76
77impl fmt::Display for Global {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.write_str(&self.path)
80 }
81}
82
83impl Extension for Global {
84 fn name(&self) -> &str {
85 "python global"
86 }
87
88 fn fallback(&self) -> Atom<'_> {
89 Atom::Str(Text::borrowed(&self.path))
90 }
91}
92
93impl Serialize for Global {
94 fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
95 Ok(Emit::Atom(Atom::Ext(ExtValue::borrowed(value))))
96 }
97}
98
99impl<'de> Deserialize<'de> for Global {
100 fn deserialize_atom(slot: &mut Slot<Self>, atom: Atom, state: &mut State) -> Result<(), Error> {
101 match atom {
102 Atom::Ext(ref ext) => match ext.downcast_ref::<Global>() {
103 Some(value) => {
104 slot.set(value.clone());
105 Ok(())
106 }
107 None => default_atom(slot, atom, state),
108 },
109 other => default_atom(slot, other, state),
110 }
111 }
112
113 fn expecting() -> Cow<'static, str> {
114 Cow::Borrowed("python global")
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
141pub struct Reference {
142 id: u64,
143}
144
145impl Reference {
146 pub const fn new(id: u64) -> Reference {
148 Reference { id }
149 }
150
151 pub const fn id(self) -> u64 {
153 self.id
154 }
155}
156
157impl Extension for Reference {
158 fn name(&self) -> &str {
159 "pickle reference"
160 }
161
162 fn fallback(&self) -> Atom<'_> {
163 Atom::Null
164 }
165}
166
167impl Serialize for Reference {
168 fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
169 Ok(Emit::Atom(Atom::Ext(ExtValue::borrowed(value))))
170 }
171}
172
173impl<'de> Deserialize<'de> for Reference {
174 fn deserialize_atom(slot: &mut Slot<Self>, atom: Atom, state: &mut State) -> Result<(), Error> {
175 match atom {
176 Atom::Ext(ref ext) => match ext.downcast_ref::<Reference>() {
177 Some(&value) => {
178 slot.set(value);
179 Ok(())
180 }
181 None => default_atom(slot, atom, state),
182 },
183 other => default_atom(slot, other, state),
184 }
185 }
186
187 fn expecting() -> Cow<'static, str> {
188 Cow::Borrowed("pickle reference")
189 }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
199pub enum Kind {
200 Tuple,
202 Set,
204 FrozenSet,
206 ByteArray,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
219pub enum Form {
220 State,
224 Slots,
227 Items,
231 Arguments,
234 Argument,
236}
237
238#[derive(Debug, Default, Clone)]
240pub(crate) struct ClassData(pub(crate) Option<Global>);
241
242#[derive(Debug, Default, Clone)]
244pub(crate) struct FormData(pub(crate) Option<Form>);
245
246#[derive(Debug, Default, Clone)]
248pub(crate) struct KindData(pub(crate) Option<Kind>);
249
250#[derive(Debug, Default, Clone)]
252pub(crate) struct SharedIdData(pub(crate) Option<u64>);
253
254pub fn take_class(state: &mut State) -> Option<Global> {
260 state.take_event::<ClassData>().and_then(|class| class.0)
261}
262
263pub fn set_class(state: &mut State, class: Global) {
271 state.event_mut::<ClassData>().0 = Some(class);
272}
273
274pub fn take_form(state: &mut State) -> Option<Form> {
278 state.take_event::<FormData>().and_then(|form| form.0)
279}
280
281pub fn set_form(state: &mut State, form: Form) {
286 state.event_mut::<FormData>().0 = Some(form);
287}
288
289pub fn take_kind(state: &mut State) -> Option<Kind> {
293 state.take_event::<KindData>().and_then(|kind| kind.0)
294}
295
296pub fn set_kind(state: &mut State, kind: Kind) {
301 state.event_mut::<KindData>().0 = Some(kind);
302}
303
304pub fn take_shared_id(state: &mut State) -> Option<u64> {
310 state.take_event::<SharedIdData>().and_then(|id| id.0)
311}
312
313pub fn set_shared_id(state: &mut State, id: u64) {
319 state.event_mut::<SharedIdData>().0 = Some(id);
320}
321
322#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
341pub struct Object<T> {
342 pub class: Option<Global>,
344 pub form: Option<Form>,
346 pub value: T,
348}
349
350impl<T> Object<T> {
351 pub fn new(class: Global, value: T) -> Object<T> {
353 Object {
354 class: Some(class),
355 form: None,
356 value,
357 }
358 }
359
360 pub fn with_form(class: Global, form: Form, value: T) -> Object<T> {
362 Object {
363 class: Some(class),
364 form: Some(form),
365 value,
366 }
367 }
368
369 pub fn into_inner(self) -> T {
371 self.value
372 }
373}
374
375impl<T: fmt::Debug> fmt::Debug for Object<T> {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 match self.class {
378 Some(ref class) => {
379 write!(f, "{} ", class)?;
380 fmt::Debug::fmt(&self.value, f)
381 }
382 None => fmt::Debug::fmt(&self.value, f),
383 }
384 }
385}
386
387impl<T: Serialize> Serialize for Object<T> {
388 fn serialize<'a>(this: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
389 let emit = T::serialize(&this.value, state)?;
391 if let Some(ref class) = this.class {
392 set_class(state, class.clone());
393 if let Some(form) = this.form {
394 set_form(state, form);
395 }
396 }
397 Ok(emit)
398 }
399
400 fn finish(this: &Self, state: &mut State) -> Result<(), Error> {
401 T::finish(&this.value, state)
402 }
403
404 fn is_optional(this: &Self) -> bool {
405 T::is_optional(&this.value)
406 }
407
408 fn container_shape(this: &Self) -> ContainerShape {
409 T::container_shape(&this.value)
410 }
411
412 fn describe(this: &Self, d: &mut dyn Describe) {
413 T::describe(&this.value, d)
414 }
415}
416
417impl<'de, T: Deserialize<'de>> Deserialize<'de> for Object<T> {
418 fn deserialize_into<'out>(
419 out: &'out mut Option<Self>,
420 state: &mut State,
421 ) -> SinkHandle<'out, 'de> {
422 SinkHandle::arena(
423 ObjectSink {
424 out,
425 slot: None,
426 compound: None,
427 class: None,
428 form: None,
429 },
430 state,
431 )
432 }
433
434 fn expecting() -> Cow<'static, str> {
435 T::expecting()
436 }
437
438 fn describe_type(d: &mut dyn Describe) {
439 T::describe_type(d)
440 }
441}
442
443struct ObjectSink<'a, 'de, T> {
444 out: &'a mut Option<Object<T>>,
445 slot: Option<T>,
448 compound: Option<OwnedSink<'de, T>>,
449 class: Option<Global>,
450 form: Option<Form>,
451}
452
453impl<'a, 'de, T: Deserialize<'de>> ObjectSink<'a, 'de, T> {
454 fn take(&mut self, state: &mut State) {
456 self.class = take_class(state);
457 self.form = take_form(state);
458 }
459
460 fn compound(&mut self, state: &mut State) -> &mut dyn Sink<'de> {
461 self.compound
462 .get_or_insert_with(|| OwnedSink::deserialize(state))
463 .get_mut()
464 }
465}
466
467impl<'a, 'de, T: Deserialize<'de>> Sink<'de> for ObjectSink<'a, 'de, T> {
468 fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
469 self.take(state);
470 let mut sink = T::deserialize_into(&mut self.slot, state);
471 sink.atom(atom, state)?;
472 sink.finish(state)
473 }
474
475 fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
476 self.take(state);
477 let mut sink = T::deserialize_into(&mut self.slot, state);
478 sink.borrowed_atom(atom, state)?;
479 sink.finish(state)
480 }
481
482 fn map(&mut self, state: &mut State) -> Result<(), Error> {
483 self.take(state);
484 self.compound(state).map(state)
485 }
486
487 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
488 self.take(state);
489 self.compound(state).seq(state)
490 }
491
492 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
493 self.compound(state).next_key(state)
494 }
495
496 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
497 self.compound(state).next_value(state)
498 }
499
500 fn value_for_key(
501 &mut self,
502 key: &str,
503 state: &mut State,
504 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
505 self.compound(state).value_for_key(key, state)
506 }
507
508 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
509 match self.compound {
510 Some(ref mut compound) => compound.get_mut().recover(err, state),
511 None => Err(err),
512 }
513 }
514
515 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
516 let value = match self.compound {
517 Some(ref mut compound) => {
518 compound.get_mut().finish(state)?;
519 compound.take()
520 }
521 None => self.slot.take(),
522 };
523 let class = self.class.take();
524 let form = self.form.take();
525 *self.out = value.map(|value| Object { class, form, value });
526 Ok(())
527 }
528
529 fn expecting(&self) -> Cow<'_, str> {
530 if let Some(ref compound) = self.compound {
531 return compound.get().expecting();
532 }
533 T::expecting()
534 }
535}