concordium_contracts_common/
impls.rs

1use crate::{constants::*, schema, traits::*, types::*};
2
3#[cfg(not(feature = "std"))]
4use alloc::{boxed::Box, collections, string::String, vec::Vec};
5use collections::{BTreeMap, BTreeSet};
6use convert::TryFrom;
7use core::cmp::Ordering;
8#[cfg(not(feature = "std"))]
9use core::{
10    convert, hash, marker,
11    mem::{transmute, MaybeUninit},
12    slice,
13};
14use hash::Hash;
15#[cfg(feature = "std")]
16use std::{
17    collections, convert, hash, marker,
18    mem::{transmute, MaybeUninit},
19    slice,
20};
21// Implementations of Serialize
22
23impl Serial for () {
24    #[inline(always)]
25    fn serial<W: Write>(&self, _out: &mut W) -> Result<(), W::Err> { Ok(()) }
26}
27
28impl Deserial for () {
29    #[inline(always)]
30    fn deserial<R: Read>(_source: &mut R) -> ParseResult<Self> { Ok(()) }
31}
32
33impl<A: Serial, B: Serial> Serial for (A, B) {
34    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
35        self.0.serial(out)?;
36        self.1.serial(out)
37    }
38}
39
40impl<A: Deserial, B: Deserial> Deserial for (A, B) {
41    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
42        let a = source.get()?;
43        let b = source.get()?;
44        Ok((a, b))
45    }
46}
47
48impl<X: Deserial, Y: Deserial, Z: Deserial> Deserial for (X, Y, Z) {
49    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
50        let a = source.get()?;
51        let b = source.get()?;
52        let c = source.get()?;
53        Ok((a, b, c))
54    }
55}
56
57impl<A: Serial, B: Serial, C: Serial> Serial for (A, B, C) {
58    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
59        self.0.serial(out)?;
60        self.1.serial(out)?;
61        self.2.serial(out)?;
62        Ok(())
63    }
64}
65
66impl<A: Deserial, B: Deserial, C: Deserial, D: Deserial> Deserial for (A, B, C, D) {
67    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
68        let a = source.get()?;
69        let b = source.get()?;
70        let c = source.get()?;
71        let d = source.get()?;
72        Ok((a, b, c, d))
73    }
74}
75
76impl<A: Serial, B: Serial, C: Serial, D: Serial> Serial for (A, B, C, D) {
77    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
78        self.0.serial(out)?;
79        self.1.serial(out)?;
80        self.2.serial(out)?;
81        self.3.serial(out)?;
82        Ok(())
83    }
84}
85
86impl<A: Deserial, B: Deserial, C: Deserial, D: Deserial, E: Deserial> Deserial for (A, B, C, D, E) {
87    #[allow(clippy::many_single_char_names)]
88    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
89        let a = source.get()?;
90        let b = source.get()?;
91        let c = source.get()?;
92        let d = source.get()?;
93        let e = source.get()?;
94        Ok((a, b, c, d, e))
95    }
96}
97
98impl<A: Serial, B: Serial, C: Serial, D: Serial, E: Serial> Serial for (A, B, C, D, E) {
99    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
100        self.0.serial(out)?;
101        self.1.serial(out)?;
102        self.2.serial(out)?;
103        self.3.serial(out)?;
104        self.4.serial(out)?;
105        Ok(())
106    }
107}
108
109impl<A: Deserial, B: Deserial, C: Deserial, D: Deserial, E: Deserial, F: Deserial> Deserial
110    for (A, B, C, D, E, F)
111{
112    #[allow(clippy::many_single_char_names)]
113    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
114        let a = source.get()?;
115        let b = source.get()?;
116        let c = source.get()?;
117        let d = source.get()?;
118        let e = source.get()?;
119        let f = source.get()?;
120        Ok((a, b, c, d, e, f))
121    }
122}
123
124impl<A: Serial, B: Serial, C: Serial, D: Serial, E: Serial, F: Serial> Serial
125    for (A, B, C, D, E, F)
126{
127    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
128        self.0.serial(out)?;
129        self.1.serial(out)?;
130        self.2.serial(out)?;
131        self.3.serial(out)?;
132        self.4.serial(out)?;
133        self.5.serial(out)?;
134        Ok(())
135    }
136}
137
138impl Serial for u8 {
139    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_u8(*self) }
140}
141
142impl Deserial for u8 {
143    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_u8() }
144}
145
146impl Serial for u16 {
147    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_u16(*self) }
148}
149
150impl Deserial for u16 {
151    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_u16() }
152}
153
154impl Serial for u32 {
155    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_u32(*self) }
156}
157
158impl Deserial for u32 {
159    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_u32() }
160}
161
162impl Serial for u64 {
163    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_u64(*self) }
164}
165
166impl Serial for u128 {
167    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
168        out.write_all(&self.to_le_bytes())
169    }
170}
171
172impl Deserial for u64 {
173    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_u64() }
174}
175
176impl Deserial for u128 {
177    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
178        let bytes = read_n_bytes!(16, source);
179        Ok(u128::from_le_bytes(bytes))
180    }
181}
182
183impl Serial for i8 {
184    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_i8(*self) }
185}
186
187impl Deserial for i8 {
188    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_i8() }
189}
190
191impl Serial for i16 {
192    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_i16(*self) }
193}
194
195impl Deserial for i16 {
196    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_i16() }
197}
198
199impl Serial for i32 {
200    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_i32(*self) }
201}
202
203impl Deserial for i32 {
204    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_i32() }
205}
206
207impl Serial for i64 {
208    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_i64(*self) }
209}
210
211impl Deserial for i64 {
212    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { source.read_i64() }
213}
214
215impl Serial for i128 {
216    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
217        out.write_all(&self.to_le_bytes())
218    }
219}
220
221impl Deserial for i128 {
222    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
223        let bytes = read_n_bytes!(16, source);
224        Ok(i128::from_le_bytes(bytes))
225    }
226}
227
228/// Serialization of `bool` encodes it as a single byte, `false` is represented
229/// by `0u8` and `true` is _only_ represented by `1u8`.
230impl Serial for bool {
231    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
232        if *self {
233            out.write_u8(1)?;
234        } else {
235            out.write_u8(0)?;
236        }
237        Ok(())
238    }
239}
240
241/// Deserializing a `bool` reads one byte, and returns the value `false` if the
242/// byte is `0u8` and `true` if the byte is `1u8`, every other value results in
243/// an error.
244impl Deserial for bool {
245    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
246        let b = source.read_u8()?;
247        match b {
248            0 => Ok(false),
249            1 => Ok(true),
250            _ => Err(ParseError::default()),
251        }
252    }
253}
254
255impl Serial for Amount {
256    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_u64(self.micro_ccd) }
257}
258
259impl Deserial for Amount {
260    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
261        source.read_u64().map(Amount::from_micro_ccd)
262    }
263}
264
265impl Serial for AccountBalance {
266    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
267        self.total.serial(out)?;
268        self.staked.serial(out)?;
269        self.locked.serial(out)?;
270        Ok(())
271    }
272}
273
274impl Deserial for AccountBalance {
275    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
276        let bytes: [u8; 24] = source.read_array()?;
277        let chunks = unsafe { transmute::<[u8; 24], [[u8; 8]; 3]>(bytes) };
278        let total = Amount::from_micro_ccd(u64::from_le_bytes(chunks[0]));
279        let staked = Amount::from_micro_ccd(u64::from_le_bytes(chunks[1]));
280        let locked = Amount::from_micro_ccd(u64::from_le_bytes(chunks[2]));
281        Self::new(total, staked, locked).ok_or_else(ParseError::default)
282    }
283}
284
285impl<Kind> Serial for NonZeroThresholdU8<Kind> {
286    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.threshold.serial(out) }
287}
288
289impl<Kind> Deserial for NonZeroThresholdU8<Kind> {
290    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
291        let threshold: u8 = u8::deserial(source)?;
292        if threshold == 0 {
293            Err(ParseError {})
294        } else {
295            Ok(Self {
296                threshold,
297                kind: marker::PhantomData,
298            })
299        }
300    }
301}
302
303impl<Kind> TryFrom<u8> for NonZeroThresholdU8<Kind> {
304    type Error = ZeroSignatureThreshold;
305
306    fn try_from(value: u8) -> Result<Self, Self::Error> {
307        if value == 0 {
308            Err(ZeroSignatureThreshold)
309        } else {
310            Ok(NonZeroThresholdU8 {
311                threshold: value,
312                kind:      marker::PhantomData,
313            })
314        }
315    }
316}
317
318impl<Kind> Clone for NonZeroThresholdU8<Kind> {
319    fn clone(&self) -> Self { *self }
320}
321
322impl<Kind> Copy for NonZeroThresholdU8<Kind> {}
323
324impl<Kind> From<NonZeroThresholdU8<Kind>> for u8 {
325    #[inline(always)]
326    fn from(value: NonZeroThresholdU8<Kind>) -> Self { value.threshold }
327}
328
329impl<Kind> PartialEq for NonZeroThresholdU8<Kind> {
330    fn eq(&self, other: &Self) -> bool { self.threshold == other.threshold }
331}
332
333impl<Kind> PartialOrd for NonZeroThresholdU8<Kind> {
334    fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
335}
336
337impl<Kind> Ord for NonZeroThresholdU8<Kind> {
338    fn cmp(&self, other: &Self) -> Ordering { self.threshold.cmp(&other.threshold) }
339}
340
341impl<Kind> PartialOrd<u8> for NonZeroThresholdU8<Kind> {
342    fn partial_cmp(&self, other: &u8) -> Option<Ordering> { self.threshold.partial_cmp(other) }
343}
344
345impl<Kind> PartialEq<u8> for NonZeroThresholdU8<Kind> {
346    fn eq(&self, other: &u8) -> bool { self.threshold == *other }
347}
348
349impl<Kind> Eq for NonZeroThresholdU8<Kind> {}
350
351impl<Kind> Hash for NonZeroThresholdU8<Kind> {
352    fn hash<H: hash::Hasher>(&self, state: &mut H) { self.threshold.hash(state) }
353}
354
355impl<Kind> NonZeroThresholdU8<Kind> {
356    /// Threshold of 1.
357    pub const ONE: Self = Self {
358        threshold: 1,
359        kind:      marker::PhantomData,
360    };
361    /// Threshold of 2.
362    pub const TWO: Self = Self {
363        threshold: 2,
364        kind:      marker::PhantomData,
365    };
366}
367
368impl schema::SchemaType for PublicKeyEd25519 {
369    fn get_type() -> crate::schema::Type { schema::Type::ByteArray(32) }
370}
371
372impl schema::SchemaType for PublicKeyEcdsaSecp256k1 {
373    fn get_type() -> crate::schema::Type { schema::Type::ByteArray(33) }
374}
375
376impl schema::SchemaType for SignatureEd25519 {
377    fn get_type() -> crate::schema::Type { schema::Type::ByteArray(64) }
378}
379
380impl schema::SchemaType for SignatureEcdsaSecp256k1 {
381    fn get_type() -> crate::schema::Type { schema::Type::ByteArray(64) }
382}
383
384impl Serial for ExchangeRate {
385    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
386        out.write_u64(self.numerator())?;
387        out.write_u64(self.denominator())
388    }
389}
390
391impl Deserial for ExchangeRate {
392    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
393        let numerator = source.read_u64()?;
394        let denominator = source.read_u64()?;
395
396        if numerator == 0 || denominator == 0 {
397            Err(ParseError::default())
398        } else {
399            Ok(ExchangeRate::new_unchecked(numerator, denominator))
400        }
401    }
402}
403
404impl Serial for ExchangeRates {
405    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
406        self.euro_per_energy.serial(out)?;
407        self.micro_ccd_per_euro.serial(out)?;
408        Ok(())
409    }
410}
411
412impl Deserial for ExchangeRates {
413    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
414        let bytes: [u8; 32] = source.read_array()?;
415        let chunks = unsafe { transmute::<[u8; 32], [[u8; 8]; 4]>(bytes) };
416
417        let euro_per_energy_numerator = u64::from_le_bytes(chunks[0]);
418        let euro_per_energy_denominator = u64::from_le_bytes(chunks[1]);
419        let micro_ccd_per_euro_numerator = u64::from_le_bytes(chunks[2]);
420        let micro_ccd_per_euro_denominator = u64::from_le_bytes(chunks[3]);
421
422        if euro_per_energy_numerator == 0
423            || euro_per_energy_denominator == 0
424            || micro_ccd_per_euro_numerator == 0
425            || micro_ccd_per_euro_denominator == 0
426        {
427            return Err(ParseError::default());
428        }
429
430        let euro_per_energy =
431            ExchangeRate::new_unchecked(euro_per_energy_numerator, euro_per_energy_denominator);
432        let micro_ccd_per_euro = ExchangeRate::new_unchecked(
433            micro_ccd_per_euro_numerator,
434            micro_ccd_per_euro_denominator,
435        );
436
437        Ok(Self {
438            euro_per_energy,
439            micro_ccd_per_euro,
440        })
441    }
442}
443
444impl Serial for Timestamp {
445    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
446        self.timestamp_millis().serial(out)
447    }
448}
449
450impl Deserial for Timestamp {
451    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
452        u64::deserial(source).map(Timestamp::from_timestamp_millis)
453    }
454}
455
456impl Serial for Duration {
457    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.millis().serial(out) }
458}
459
460impl Deserial for Duration {
461    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
462        u64::deserial(source).map(Duration::from_millis)
463    }
464}
465
466/// Serialized by writing an `u32` representing the number of bytes for a
467/// utf8-encoding of the string, then writing the bytes. Similar to `Vec<_>`.
468impl Serial for &str {
469    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
470        let bytes = self.as_bytes();
471        let len = bytes.len() as u32;
472        len.serial(out)?;
473        out.write_all(bytes)
474    }
475}
476
477impl<A: Serial> Serial for &A {
478    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { (*self).serial(out) }
479}
480
481/// Serialized by writing an `u32` representing the number of bytes for a
482/// utf8-encoding of the string, then writing the bytes. Similar to `&str`.
483impl Serial for String {
484    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.as_str().serial(out) }
485}
486
487/// Deserial by reading an `u32` representing the number of bytes, then takes
488/// that number of bytes and tries to decode using utf8.
489impl Deserial for String {
490    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
491        let bytes = Vec::deserial(source)?;
492        let res = String::from_utf8(bytes).map_err(|_| ParseError::default())?;
493        Ok(res)
494    }
495}
496
497impl<T: Serial> Serial for Box<T> {
498    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.as_ref().serial(out) }
499}
500
501impl<T: Deserial> Deserial for Box<T> {
502    #[inline]
503    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
504        let t = T::deserial(source)?;
505        Ok(Box::new(t))
506    }
507}
508
509impl<C: ?Sized> Serial for marker::PhantomData<C> {
510    #[inline(always)]
511    fn serial<W: Write>(&self, _out: &mut W) -> Result<(), W::Err> { Ok(()) }
512}
513
514impl<C: ?Sized> Deserial for marker::PhantomData<C> {
515    #[inline(always)]
516    fn deserial<R: Read>(_source: &mut R) -> ParseResult<Self> { Ok(marker::PhantomData) }
517}
518
519/// Serialized if the `Option` is a `None` we write `0u8`. If `Some`, we write
520/// `1u8` followed by the serialization of the contained `T`.
521impl<T: Serial> Serial for Option<T> {
522    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
523        match self {
524            None => out.write_u8(0),
525            Some(t) => {
526                out.write_u8(1)?;
527                t.serial(out)
528            }
529        }
530    }
531}
532
533/// Deserial by reading one byte, where `0u8` represents `None` and `1u8`
534/// represents `Some`, every other value results in an error.
535/// In the case of `Some` we deserialize using the contained `T`.
536impl<T: Deserial> Deserial for Option<T> {
537    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
538        let idx: u8 = source.get()?;
539        match idx {
540            0 => Ok(None),
541            1 => {
542                let t = T::deserial(source)?;
543                Ok(Some(t))
544            }
545            _ => Err(ParseError::default()),
546        }
547    }
548}
549
550impl Serial for AccountAddress {
551    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_all(&self.0) }
552}
553
554impl Deserial for AccountAddress {
555    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
556        let bytes = {
557            // This deliberately does not initialize the array up-front.
558            // Initialization is not needed, and costs quite a bit of code space in the Wasm
559            // generated code. Since account addresses
560            let mut bytes: MaybeUninit<[u8; 32]> = MaybeUninit::uninit();
561            let write_bytes =
562                unsafe { slice::from_raw_parts_mut(bytes.as_mut_ptr() as *mut u8, 32) };
563            source.read_exact(write_bytes)?;
564            unsafe { bytes.assume_init() }
565        };
566        Ok(AccountAddress(bytes))
567    }
568}
569
570impl Serial for ContractAddress {
571    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
572        out.write_u64(self.index)?;
573        out.write_u64(self.subindex)
574    }
575}
576
577impl Deserial for ContractAddress {
578    #[inline]
579    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
580        let index = source.get()?;
581        let subindex = source.get()?;
582        Ok(ContractAddress {
583            index,
584            subindex,
585        })
586    }
587}
588
589impl Serial for Address {
590    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
591        match self {
592            Address::Account(ref acc) => {
593                out.write_u8(0)?;
594                acc.serial(out)
595            }
596            Address::Contract(ref cnt) => {
597                out.write_u8(1)?;
598                cnt.serial(out)
599            }
600        }
601    }
602}
603
604impl Deserial for Address {
605    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
606        let tag = u8::deserial(source)?;
607        match tag {
608            0 => Ok(Address::Account(source.get()?)),
609            1 => Ok(Address::Contract(source.get()?)),
610            _ => Err(ParseError::default()),
611        }
612    }
613}
614
615impl<'a> Serial for ContractName<'a> {
616    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
617        let name = self.get_chain_name();
618        let len = name.len() as u16;
619        len.serial(out)?;
620        serial_vector_no_length(name.as_bytes(), out)
621    }
622}
623
624impl Serial for OwnedContractName {
625    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
626        self.as_contract_name().serial(out)
627    }
628}
629
630impl Deserial for OwnedContractName {
631    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
632        let len: u16 = source.get()?;
633        let bytes = deserial_vector_no_length(source, len as usize)?;
634        let name = String::from_utf8(bytes).map_err(|_| ParseError::default())?;
635        let owned_contract_name =
636            OwnedContractName::new(name).map_err(|_| ParseError::default())?;
637        Ok(owned_contract_name)
638    }
639}
640
641impl<'a> Serial for ReceiveName<'a> {
642    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
643        let name = self.get_chain_name();
644        let len = name.len() as u16;
645        len.serial(out)?;
646        serial_vector_no_length(name.as_bytes(), out)
647    }
648}
649
650impl Serial for OwnedReceiveName {
651    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
652        self.as_receive_name().serial(out)
653    }
654}
655
656impl Deserial for OwnedReceiveName {
657    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
658        let len: u16 = source.get()?;
659        let bytes = deserial_vector_no_length(source, len as usize)?;
660        let name = String::from_utf8(bytes).map_err(|_| ParseError::default())?;
661        let owned_receive_name = OwnedReceiveName::new(name).map_err(|_| ParseError::default())?;
662        Ok(owned_receive_name)
663    }
664}
665
666impl<'a> Serial for EntrypointName<'a> {
667    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
668        let len = self.0.len() as u16;
669        len.serial(out)?;
670        serial_vector_no_length(self.0.as_bytes(), out)
671    }
672}
673
674impl Serial for OwnedEntrypointName {
675    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
676        self.as_entrypoint_name().serial(out)
677    }
678}
679
680impl Deserial for OwnedEntrypointName {
681    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
682        let len: u16 = source.get()?;
683        let bytes = deserial_vector_no_length(source, len as usize)?;
684        let name = String::from_utf8(bytes).map_err(|_| ParseError::default())?;
685        let owned_entrypoint_name = Self::new(name).map_err(|_| ParseError::default())?;
686        Ok(owned_entrypoint_name)
687    }
688}
689
690impl<'a> Serial for Parameter<'a> {
691    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
692        let len = self.0.len() as u16;
693        len.serial(out)?;
694        out.write_all(self.0)
695    }
696}
697
698impl Serial for OwnedParameter {
699    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
700        self.as_parameter().serial(out)
701    }
702}
703
704impl Deserial for OwnedParameter {
705    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
706        let len: u16 = source.get()?;
707        let bytes = deserial_vector_no_length(source, len as usize)?;
708        Ok(Self(bytes))
709    }
710}
711
712impl Serial for ChainMetadata {
713    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.slot_time.serial(out) }
714}
715
716impl Deserial for ChainMetadata {
717    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
718        let slot_time = source.get()?;
719        Ok(Self {
720            slot_time,
721        })
722    }
723}
724
725impl<K: Serial + Ord> SerialCtx for BTreeSet<K> {
726    fn serial_ctx<W: Write>(
727        &self,
728        size_len: schema::SizeLength,
729        out: &mut W,
730    ) -> Result<(), W::Err> {
731        schema::serial_length(self.len(), size_len, out)?;
732        serial_set_no_length(self, out)
733    }
734}
735
736impl<K: Deserial + Ord> DeserialCtx for BTreeSet<K> {
737    fn deserial_ctx<R: Read>(
738        size_len: schema::SizeLength,
739        ensure_ordered: bool,
740        source: &mut R,
741    ) -> ParseResult<Self> {
742        let len = schema::deserial_length(source, size_len)?;
743        if ensure_ordered {
744            deserial_set_no_length(source, len)
745        } else {
746            deserial_set_no_length_no_order_check(source, len)
747        }
748    }
749}
750
751impl<K: Serial + Ord, V: Serial> SerialCtx for BTreeMap<K, V> {
752    fn serial_ctx<W: Write>(
753        &self,
754        size_len: schema::SizeLength,
755        out: &mut W,
756    ) -> Result<(), W::Err> {
757        schema::serial_length(self.len(), size_len, out)?;
758        serial_map_no_length(self, out)
759    }
760}
761
762impl<K: Deserial + Ord, V: Deserial> DeserialCtx for BTreeMap<K, V> {
763    fn deserial_ctx<R: Read>(
764        size_len: schema::SizeLength,
765        ensure_ordered: bool,
766        source: &mut R,
767    ) -> ParseResult<Self> {
768        let len = schema::deserial_length(source, size_len)?;
769        if ensure_ordered {
770            deserial_map_no_length(source, len)
771        } else {
772            deserial_map_no_length_no_order_check(source, len)
773        }
774    }
775}
776
777/// Serialization for HashSet given a size_len.
778/// Values are not serialized in any particular order.
779impl<K: Serial> SerialCtx for HashSet<K> {
780    fn serial_ctx<W: Write>(
781        &self,
782        size_len: schema::SizeLength,
783        out: &mut W,
784    ) -> Result<(), W::Err> {
785        schema::serial_length(self.len(), size_len, out)?;
786        serial_hashset_no_length(self, out)
787    }
788}
789
790/// Deserialization for HashSet given a size_len.
791/// Values are not verified to be in any particular order and setting
792/// ensure_ordering have no effect.
793impl<K: Deserial + Eq + Hash> DeserialCtx for HashSet<K> {
794    fn deserial_ctx<R: Read>(
795        size_len: schema::SizeLength,
796        _ensure_ordered: bool,
797        source: &mut R,
798    ) -> ParseResult<Self> {
799        let len = schema::deserial_length(source, size_len)?;
800        deserial_hashset_no_length(source, len)
801    }
802}
803
804/// Serialization for HashMap given a size_len.
805/// Keys are not serialized in any particular order.
806impl<K: Serial, V: Serial> SerialCtx for HashMap<K, V> {
807    fn serial_ctx<W: Write>(
808        &self,
809        size_len: schema::SizeLength,
810        out: &mut W,
811    ) -> Result<(), W::Err> {
812        schema::serial_length(self.len(), size_len, out)?;
813        serial_hashmap_no_length(self, out)
814    }
815}
816
817/// Deserialization for HashMap given a size_len.
818/// Keys are not verified to be in any particular order and setting
819/// ensure_ordering have no effect.
820impl<K: Deserial + Eq + Hash, V: Deserial> DeserialCtx for HashMap<K, V> {
821    fn deserial_ctx<R: Read>(
822        size_len: schema::SizeLength,
823        _ensure_ordered: bool,
824        source: &mut R,
825    ) -> ParseResult<Self> {
826        let len = schema::deserial_length(source, size_len)?;
827        deserial_hashmap_no_length(source, len)
828    }
829}
830
831impl<T: Serial> SerialCtx for &[T] {
832    fn serial_ctx<W: Write>(
833        &self,
834        size_len: schema::SizeLength,
835        out: &mut W,
836    ) -> Result<(), W::Err> {
837        schema::serial_length(self.len(), size_len, out)?;
838        serial_vector_no_length(self, out)
839    }
840}
841
842impl<T: Serial> SerialCtx for Vec<T> {
843    fn serial_ctx<W: Write>(
844        &self,
845        size_len: schema::SizeLength,
846        out: &mut W,
847    ) -> Result<(), W::Err> {
848        self.as_slice().serial_ctx(size_len, out)
849    }
850}
851
852impl<T: Deserial> DeserialCtx for Vec<T> {
853    fn deserial_ctx<R: Read>(
854        size_len: schema::SizeLength,
855        _ensure_ordered: bool,
856        source: &mut R,
857    ) -> ParseResult<Self> {
858        let len = schema::deserial_length(source, size_len)?;
859        deserial_vector_no_length(source, len)
860    }
861}
862
863impl SerialCtx for &str {
864    fn serial_ctx<W: Write>(
865        &self,
866        size_len: schema::SizeLength,
867        out: &mut W,
868    ) -> Result<(), W::Err> {
869        schema::serial_length(self.len(), size_len, out)?;
870        serial_vector_no_length(self.as_bytes(), out)
871    }
872}
873
874impl SerialCtx for String {
875    fn serial_ctx<W: Write>(
876        &self,
877        size_len: schema::SizeLength,
878        out: &mut W,
879    ) -> Result<(), W::Err> {
880        self.as_str().serial_ctx(size_len, out)
881    }
882}
883
884impl DeserialCtx for String {
885    fn deserial_ctx<R: Read>(
886        size_len: schema::SizeLength,
887        _ensure_ordered: bool,
888        source: &mut R,
889    ) -> ParseResult<Self> {
890        let len = schema::deserial_length(source, size_len)?;
891        let bytes = deserial_vector_no_length(source, len)?;
892        let res = String::from_utf8(bytes).map_err(|_| ParseError::default())?;
893        Ok(res)
894    }
895}
896
897/// Write a slice of elements, without including length information.
898/// This is intended to be used either when the length is statically known,
899/// or when the length is serialized independently as part of a bigger
900/// structure.
901pub fn serial_vector_no_length<W: Write, T: Serial>(xs: &[T], out: &mut W) -> Result<(), W::Err> {
902    for x in xs {
903        x.serial(out)?;
904    }
905    Ok(())
906}
907
908/// Read a vector given a length.
909pub fn deserial_vector_no_length<R: Read, T: Deserial>(
910    reader: &mut R,
911    len: usize,
912) -> ParseResult<Vec<T>> {
913    let mut vec = Vec::with_capacity(core::cmp::min(len, MAX_PREALLOCATED_CAPACITY));
914    for _ in 0..len {
915        vec.push(T::deserial(reader)?);
916    }
917    Ok(vec)
918}
919
920/// Write a Map as a list of key-value pairs ordered by the key, without the
921/// length information.
922pub fn serial_map_no_length<W: Write, K: Serial, V: Serial>(
923    map: &BTreeMap<K, V>,
924    out: &mut W,
925) -> Result<(), W::Err> {
926    for (k, v) in map.iter() {
927        k.serial(out)?;
928        v.serial(out)?;
929    }
930    Ok(())
931}
932
933/// Read a [BTreeMap](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html) as a list of key-value pairs given some length.
934/// NB: This ensures there are no duplicates, hence the specialized type.
935/// Moreover this will only succeed if keys are listed in order.
936pub fn deserial_map_no_length<R: Read, K: Deserial + Ord, V: Deserial>(
937    source: &mut R,
938    len: usize,
939) -> ParseResult<BTreeMap<K, V>> {
940    let mut out = BTreeMap::new();
941    let mut x = None;
942    for _ in 0..len {
943        let k = source.get()?;
944        let v = source.get()?;
945        if let Some((old_k, old_v)) = x.take() {
946            if k > old_k {
947                out.insert(old_k, old_v);
948            } else {
949                return Err(ParseError::default());
950            }
951        }
952        x = Some((k, v));
953    }
954    if let Some((k, v)) = x {
955        out.insert(k, v);
956    }
957    Ok(out)
958}
959
960/// Read a [BTreeMap](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html) as a list of key-value pairs given some length.
961/// Slightly faster version of `deserial_map_no_length` as it is skipping the
962/// order checking
963pub fn deserial_map_no_length_no_order_check<R: Read, K: Deserial + Ord, V: Deserial>(
964    source: &mut R,
965    len: usize,
966) -> ParseResult<BTreeMap<K, V>> {
967    let mut out = BTreeMap::new();
968    for _ in 0..len {
969        let k = source.get()?;
970        let v = source.get()?;
971        if out.insert(k, v).is_some() {
972            return Err(ParseError::default());
973        }
974    }
975    Ok(out)
976}
977
978/// Write a HashMap as a list of key-value pairs in to particular order, without
979/// the length information.
980pub fn serial_hashmap_no_length<W: Write, K: Serial, V: Serial>(
981    map: &HashMap<K, V>,
982    out: &mut W,
983) -> Result<(), W::Err> {
984    for (k, v) in map.iter() {
985        k.serial(out)?;
986        v.serial(out)?;
987    }
988    Ok(())
989}
990
991/// Read a [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html) as a list of key-value pairs given some length.
992pub fn deserial_hashmap_no_length<R: Read, K: Deserial + Eq + Hash, V: Deserial>(
993    source: &mut R,
994    len: usize,
995) -> ParseResult<HashMap<K, V>> {
996    let mut out = HashMap::default();
997    for _ in 0..len {
998        let k = source.get()?;
999        let v = source.get()?;
1000        if out.insert(k, v).is_some() {
1001            return Err(ParseError::default());
1002        }
1003    }
1004    Ok(out)
1005}
1006
1007/// Write a [BTreeSet](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html) as an ascending list of keys, without the length information.
1008pub fn serial_set_no_length<W: Write, K: Serial>(
1009    map: &BTreeSet<K>,
1010    out: &mut W,
1011) -> Result<(), W::Err> {
1012    for k in map.iter() {
1013        k.serial(out)?;
1014    }
1015    Ok(())
1016}
1017
1018/// Read a [BTreeSet](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html) as a list of keys, given some length.
1019/// NB: This ensures there are no duplicates, hence the specialized type.
1020/// Moreover this will only succeed if keys are listed in order.
1021pub fn deserial_set_no_length<R: Read, K: Deserial + Ord>(
1022    source: &mut R,
1023    len: usize,
1024) -> ParseResult<BTreeSet<K>> {
1025    let mut out = BTreeSet::new();
1026    let mut prev = None;
1027    for _ in 0..len {
1028        let key = source.get()?;
1029        if let Some(old_key) = prev.take() {
1030            if key > old_key {
1031                out.insert(old_key);
1032            } else {
1033                return Err(ParseError::default());
1034            }
1035        }
1036        prev = Some(key);
1037    }
1038    if let Some(key) = prev {
1039        out.insert(key);
1040    }
1041    Ok(out)
1042}
1043
1044/// Write a [HashSet](https://doc.rust-lang.org/std/collections/struct.HashSet.html) as a list of keys in no particular order, without the length information.
1045pub fn serial_hashset_no_length<W: Write, K: Serial>(
1046    map: &HashSet<K>,
1047    out: &mut W,
1048) -> Result<(), W::Err> {
1049    for k in map.iter() {
1050        k.serial(out)?;
1051    }
1052    Ok(())
1053}
1054
1055/// Read a [HashSet](https://doc.rust-lang.org/std/collections/struct.HashSet.html) as a list of keys, given some length.
1056/// NB: This ensures there are no duplicates.
1057pub fn deserial_hashset_no_length<R: Read, K: Deserial + Eq + Hash>(
1058    source: &mut R,
1059    len: usize,
1060) -> ParseResult<HashSet<K>> {
1061    let mut out = HashSet::default();
1062    for _ in 0..len {
1063        let key = source.get()?;
1064        if !out.insert(key) {
1065            return Err(ParseError::default());
1066        }
1067    }
1068    Ok(out)
1069}
1070
1071/// Read a [BTreeSet](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html) as an list of key-value pairs given some length.
1072/// Slightly faster version of `deserial_set_no_length` as it is skipping the
1073/// order checking. The only check that is made to the set is that there are no
1074/// duplicates.
1075pub fn deserial_set_no_length_no_order_check<R: Read, K: Deserial + Ord>(
1076    source: &mut R,
1077    len: usize,
1078) -> ParseResult<BTreeSet<K>> {
1079    let mut out = BTreeSet::new();
1080    for _ in 0..len {
1081        let key = source.get()?;
1082        if !out.insert(key) {
1083            return Err(ParseError::default());
1084        }
1085    }
1086    Ok(out)
1087}
1088
1089/// Serialized by writing an `u32` representing the number of elements, followed
1090/// by the elements serialized according to their type `T`.
1091impl<T: Serial> Serial for Vec<T> {
1092    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1093        let len = self.len() as u32;
1094        len.serial(out)?;
1095        serial_vector_no_length(self, out)
1096    }
1097}
1098
1099/// Deserialized by reading an `u32` representing the number of elements, then
1100/// deserializing that many elements of type `T`.
1101impl<T: Deserial> Deserial for Vec<T> {
1102    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1103        let len: u32 = source.get()?;
1104        deserial_vector_no_length(source, len as usize)
1105    }
1106}
1107
1108/// The serialization of maps encodes their size as a u32. This should be
1109/// sufficient for all realistic use cases in smart contracts.
1110/// They are serialized in ascending order.
1111impl<K: Serial + Ord, V: Serial> Serial for BTreeMap<K, V> {
1112    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1113        let len = self.len() as u32;
1114        len.serial(out)?;
1115        serial_map_no_length(self, out)
1116    }
1117}
1118
1119/// The deserialization of maps assumes their size is a u32.
1120///
1121/// <b style="color: darkred">WARNING</b>: Deserialization **does not** ensure
1122/// the ordering of the keys, it only ensures that there are no duplicates.
1123/// Serializing a `BTreeMap` via its `Serial` instance will lay out elements
1124/// by the increasing order of keys. As a consequence deserializing, and
1125/// serializing back is in general not the identity. This could have
1126/// consequences if the data is hashed, or the byte representation
1127/// is used in some other way directly. In those cases the a canonical
1128/// order should be ensured to avoid subtle, difficult to diagnose,
1129/// bugs.
1130impl<K: Deserial + Ord, V: Deserial> Deserial for BTreeMap<K, V> {
1131    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1132        let len: u32 = source.get()?;
1133        deserial_map_no_length_no_order_check(source, len as usize)
1134    }
1135}
1136
1137/// The serialization of maps encodes their size as a u32. This should be
1138/// sufficient for all realistic use cases in smart contracts.
1139/// They are serialized in no particular order.
1140impl<K: Serial, V: Serial> Serial for HashMap<K, V> {
1141    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1142        let len = self.len() as u32;
1143        len.serial(out)?;
1144        serial_hashmap_no_length(self, out)
1145    }
1146}
1147
1148/// The deserialization of maps assumes their size is a u32.
1149///
1150/// <b style="color: darkred">WARNING</b>: Deserialization only ensures that
1151/// there are no duplicates. Serializing a `HashMap` via its `Serial` instance
1152/// will not lay out elements in a particular order. As a consequence
1153/// deserializing, and serializing back is in general not the identity. This
1154/// could have consequences if the data is hashed, or the byte representation
1155/// is used in some other way directly. In those cases use a `BTreeMap` instead.
1156impl<K: Deserial + Hash + Eq, V: Deserial> Deserial for HashMap<K, V> {
1157    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1158        let len: u32 = source.get()?;
1159        deserial_hashmap_no_length(source, len as usize)
1160    }
1161}
1162
1163/// The serialization of sets encodes their size as a u32. This should be
1164/// sufficient for all realistic use cases in smart contracts.
1165/// They are serialized in canonical order (increasing)
1166impl<K: Serial + Ord> Serial for BTreeSet<K> {
1167    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1168        let len = self.len() as u32;
1169        len.serial(out)?;
1170        serial_set_no_length(self, out)
1171    }
1172}
1173
1174/// The deserialization of sets assumes their size is a u32.
1175///
1176/// <b style="color: darkred">WARNING</b>: Deserialization **does not** ensure
1177/// the ordering of the keys, it only ensures that there are no duplicates.
1178/// Serializing a `BTreeSet` via its `Serial` instance will lay out elements
1179/// by the increasing order. As a consequence deserializing, and
1180/// serializing back is in general not the identity. This could have
1181/// consequences if the data is hashed, or the byte representation
1182/// is used in some other way directly. In those cases a canonical
1183/// order should be ensured to avoid subtle, difficult to diagnose,
1184/// bugs.
1185impl<K: Deserial + Ord> Deserial for BTreeSet<K> {
1186    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1187        let len: u32 = source.get()?;
1188        deserial_set_no_length_no_order_check(source, len as usize)
1189    }
1190}
1191
1192// The serialization of sets encodes their size as a u32. This should be
1193/// sufficient for all realistic use cases in smart contracts.
1194/// They are serialized in no particular order.
1195impl<K: Serial> Serial for HashSet<K> {
1196    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1197        let len = self.len() as u32;
1198        len.serial(out)?;
1199        serial_hashset_no_length(self, out)
1200    }
1201}
1202
1203/// The deserialization of sets assumes their size is a u32.
1204///
1205/// <b style="color: darkred">WARNING</b>: Deserialization only ensures that
1206/// there are no duplicates. Serializing a `HashSet` via its `Serial` instance
1207/// will not lay out elements in any particular order. As a consequence
1208/// deserializing, and serializing back is in general not the identity. This
1209/// could have consequences if the data is hashed, or the byte representation
1210/// is used in some other way directly. In those cases use a `BTreeSet` instead.
1211impl<K: Deserial + Hash + Eq> Deserial for HashSet<K> {
1212    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1213        let len: u32 = source.get()?;
1214        deserial_hashset_no_length(source, len as usize)
1215    }
1216}
1217
1218/// Serialize the array by writing elements consecutively starting at 0.
1219/// Since the length of the array is known statically it is not written out
1220/// explicitly. Thus serialization of the array A and the slice &A[..] differ.
1221impl<T: Serial, const N: usize> Serial for [T; N] {
1222    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1223        for elem in self.iter() {
1224            elem.serial(out)?;
1225        }
1226        Ok(())
1227    }
1228}
1229
1230impl<T: Deserial, const N: usize> Deserial for [T; N] {
1231    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1232        let mut data: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() };
1233        for item in data.iter_mut() {
1234            *item = MaybeUninit::new(T::deserial(source)?);
1235        }
1236        Ok(unsafe { data.as_ptr().cast::<[T; N]>().read() })
1237    }
1238}
1239
1240impl Address {
1241    pub fn matches_account(&self, acc: &AccountAddress) -> bool {
1242        if let Address::Account(ref my_acc) = self {
1243            my_acc == acc
1244        } else {
1245            false
1246        }
1247    }
1248
1249    pub fn matches_contract(&self, cnt: &ContractAddress) -> bool {
1250        if let Address::Contract(ref my_cnt) = self {
1251            my_cnt == cnt
1252        } else {
1253            false
1254        }
1255    }
1256
1257    /// Return `true` if and only if the address is an account address.
1258    pub fn is_account(&self) -> bool { matches!(self, Address::Account(_)) }
1259
1260    /// Return `true` if and only if the address is a contract address.
1261    pub fn is_contract(&self) -> bool { matches!(self, Address::Contract(_)) }
1262}
1263
1264impl Serial for AttributeTag {
1265    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.0.serial(out) }
1266}
1267
1268impl Deserial for AttributeTag {
1269    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> { Ok(AttributeTag(source.get()?)) }
1270}
1271
1272impl Serial for AttributeValue {
1273    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1274        out.write_all(&self.inner[..=self.len()]) // Writes the length (u8) +
1275                                                  // all the values.
1276    }
1277}
1278
1279impl Deserial for AttributeValue {
1280    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1281        let mut buf = [0u8; 32];
1282        let len: u8 = source.get()?;
1283        buf[0] = len;
1284        if len > 31 {
1285            return Err(ParseError::default());
1286        }
1287        source.read_exact(&mut buf[1..=len as usize])?;
1288        Ok(unsafe { AttributeValue::new_unchecked(buf) })
1289    }
1290}
1291
1292impl Serial for OwnedPolicy {
1293    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
1294        self.identity_provider.serial(out)?;
1295        self.created_at.serial(out)?;
1296        self.valid_to.serial(out)?;
1297        (self.items.len() as u16).serial(out)?;
1298        for item in self.items.iter() {
1299            item.0.serial(out)?;
1300            item.1.serial(out)?;
1301        }
1302        Ok(())
1303    }
1304}
1305
1306impl Deserial for OwnedPolicy {
1307    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
1308        let identity_provider = source.get()?;
1309        let created_at = source.get()?;
1310        let valid_to = source.get()?;
1311        let len: u16 = source.get()?;
1312        let mut items = Vec::with_capacity(len as usize);
1313        for _ in 0..len {
1314            let tag = AttributeTag::deserial(source)?;
1315            let value = AttributeValue::deserial(source)?;
1316            items.push((tag, value))
1317        }
1318        Ok(Self {
1319            identity_provider,
1320            created_at,
1321            valid_to,
1322            items,
1323        })
1324    }
1325}
1326
1327impl<T> Cursor<T> {
1328    pub fn new(data: T) -> Self {
1329        Cursor {
1330            offset: 0,
1331            data,
1332        }
1333    }
1334}
1335
1336impl<T: AsRef<[u8]>> Read for Cursor<T> {
1337    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize> {
1338        let mut len = self.data.as_ref().len() - self.offset;
1339        if len > buf.len() {
1340            len = buf.len();
1341        }
1342        if len > 0 {
1343            buf[0..len].copy_from_slice(&self.data.as_ref()[self.offset..self.offset + len]);
1344            self.offset += len;
1345            Ok(len)
1346        } else {
1347            Ok(0)
1348        }
1349    }
1350}
1351
1352// This implementation deviates from [`std::io::Chain`](https://doc.rust-lang.org/std/io/struct.Chain.html#impl-Read-for-Chain%3CT,+U%3E)
1353// since the usecase where we need this only have a mutable reference available.
1354impl<'a, 'b, T: Read, U: Read> Read for Chain<&'a mut T, &'b mut U> {
1355    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize> {
1356        if !self.done_first {
1357            match self.first.read(buf)? {
1358                0 if !buf.is_empty() => self.done_first = true,
1359                n => return Ok(n),
1360            }
1361        }
1362        self.second.read(buf)
1363    }
1364}
1365
1366impl<T: AsRef<[u8]>> HasSize for T {
1367    fn size(&self) -> u32 { self.as_ref().len() as u32 }
1368}
1369
1370impl<T: AsRef<[u8]>> AsRef<[u8]> for Cursor<T> {
1371    fn as_ref(&self) -> &[u8] { self.data.as_ref() }
1372}
1373
1374impl<T: HasSize> Seek for Cursor<T> {
1375    type Err = ();
1376
1377    fn seek(&mut self, pos: SeekFrom) -> Result<u32, Self::Err> {
1378        use SeekFrom::*;
1379        let end = self.data.size();
1380        match pos {
1381            Start(offset) => {
1382                if offset <= end {
1383                    self.offset = offset as usize;
1384                    Ok(offset)
1385                } else {
1386                    Err(())
1387                }
1388            }
1389            End(delta) => {
1390                if delta > 0 {
1391                    Err(()) // cannot seek beyond the end
1392                } else {
1393                    // due to two's complement representation of values we do not have to
1394                    // distinguish on whether we go forward or backwards. Reinterpreting the bits
1395                    // and adding unsigned values is the same as subtracting the
1396                    // absolute value.
1397                    let new_offset = end.wrapping_add(delta as u32);
1398                    if new_offset <= end {
1399                        self.offset = new_offset as usize;
1400                        Ok(new_offset)
1401                    } else {
1402                        Err(())
1403                    }
1404                }
1405            }
1406            Current(delta) => {
1407                // due to two's complement representation of values we do not have to
1408                // distinguish on whether we go forward or backwards.
1409                let current_offset = u32::try_from(self.offset).map_err(|_| ())?;
1410                let new_offset: u32 = current_offset.wrapping_add(delta as u32);
1411                if new_offset <= end {
1412                    self.offset = new_offset as usize;
1413                    Ok(new_offset)
1414                } else {
1415                    Err(())
1416                }
1417            }
1418        }
1419    }
1420
1421    #[inline(always)]
1422    fn cursor_position(&self) -> u32 { self.offset as u32 }
1423}
1424
1425impl Write for Cursor<&mut Vec<u8>> {
1426    type Err = ();
1427
1428    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Err> {
1429        if buf.is_empty() {
1430            Ok(0)
1431        } else {
1432            // remaining capacity.
1433            let remaining_len = self.data.len() - self.offset;
1434            let (to_write, to_extend): (_, &[u8]) = {
1435                if remaining_len >= buf.len() {
1436                    (buf, &[])
1437                } else {
1438                    (&buf[..remaining_len], &buf[remaining_len..])
1439                }
1440            };
1441            self.data[self.offset..self.offset + to_write.len()].copy_from_slice(to_write);
1442            self.data.extend_from_slice(to_extend);
1443            self.offset += buf.len();
1444            Ok(buf.len())
1445        }
1446    }
1447}
1448
1449/// Serialize the given value to a freshly allocated vector of bytes using
1450/// the provided `Serial` instance.
1451///
1452/// This should only be used as a helper function at the top-level, and not in
1453/// implementations of `Serial`.
1454pub fn to_bytes<S: Serial>(x: &S) -> Vec<u8> {
1455    let mut out = Vec::new();
1456    let mut cursor = Cursor::new(&mut out);
1457    x.serial(&mut cursor).expect("Writing to a vector should succeed.");
1458    out
1459}
1460
1461/// Dual to `to_bytes`.
1462#[inline]
1463pub fn from_bytes<S: Deserial>(source: &[u8]) -> ParseResult<S> {
1464    let mut cursor = Cursor::new(source);
1465    cursor.get()
1466}
1467
1468#[cfg(test)]
1469mod test {
1470    use super::*;
1471    #[test]
1472    fn test_u64_array_deserial_serial_is_id() {
1473        let xs: [u64; 1] = [123];
1474        let bytes = to_bytes(&xs);
1475        let xs2: ParseResult<[u64; 1]> = from_bytes(&bytes);
1476        assert_eq!(
1477            xs,
1478            xs2.unwrap(),
1479            "Serializing and then deserializing should return original value."
1480        );
1481    }
1482
1483    #[test]
1484    fn test_string_array_deserial_serial_is_id() {
1485        let xs: [String; 1] = ["hello".to_string()];
1486        let bytes = to_bytes(&xs);
1487        let xs2: ParseResult<[String; 1]> = from_bytes(&bytes);
1488        assert_eq!(
1489            xs,
1490            xs2.unwrap(),
1491            "Serializing and then deserializing should return original value."
1492        );
1493    }
1494
1495    #[test]
1496    fn test_cursor_seek_start() {
1497        let bytes = [0u8; 10];
1498        let mut cursor = Cursor::new(&bytes);
1499
1500        let result = cursor.seek(SeekFrom::Start(8));
1501        let position = result.expect("Seek should succeed");
1502
1503        assert_eq!(position, 8, "Seek moved to the wrong position");
1504    }
1505
1506    #[test]
1507    fn test_cursor_seek_start_at_the_end() {
1508        let bytes = [0u8; 10];
1509        let mut cursor = Cursor::new(&bytes);
1510
1511        let result = cursor.seek(SeekFrom::Start(10));
1512        let position = result.expect("Seek should succeed");
1513
1514        assert_eq!(position, 10, "Seek moved to the wrong position");
1515    }
1516
1517    #[test]
1518    fn test_cursor_seek_start_fails_beyond_end() {
1519        let bytes = [0u8; 10];
1520        let mut cursor = Cursor::new(&bytes);
1521
1522        let result = cursor.seek(SeekFrom::Start(11));
1523        result.expect_err("Should have failed to seek beyond end of data");
1524    }
1525
1526    #[test]
1527    fn test_cursor_seek_end() {
1528        let bytes = [0u8; 10];
1529        let mut cursor = Cursor::new(&bytes);
1530
1531        let result = cursor.seek(SeekFrom::End(-8));
1532        let position = result.expect("Seek should succeed");
1533
1534        assert_eq!(position, 2, "Seek moved to the wrong position");
1535    }
1536
1537    #[test]
1538    fn test_cursor_seek_end_at_the_start() {
1539        let bytes = [0u8; 10];
1540        let mut cursor = Cursor::new(&bytes);
1541
1542        let result = cursor.seek(SeekFrom::End(-10));
1543        let position = result.expect("Seek should succeed");
1544
1545        assert_eq!(position, 0, "Seek moved to the wrong position");
1546    }
1547
1548    #[test]
1549    fn test_cursor_seek_end_at_the_end() {
1550        let bytes = [0u8; 10];
1551        let mut cursor = Cursor::new(&bytes);
1552
1553        let result = cursor.seek(SeekFrom::End(0));
1554        let position = result.expect("Seek should succeed");
1555
1556        assert_eq!(position, 10, "Seek moved to the wrong position");
1557    }
1558
1559    #[test]
1560    fn test_cursor_seek_end_fails_before_start() {
1561        let bytes = [0u8; 10];
1562        let mut cursor = Cursor::new(&bytes);
1563
1564        let result = cursor.seek(SeekFrom::End(-11));
1565        result.expect_err("Should have failed to seek before start of data");
1566    }
1567
1568    #[test]
1569    fn test_cursor_seek_end_fails_beyond_end() {
1570        let bytes = [0u8; 10];
1571        let mut cursor = Cursor::new(&bytes);
1572
1573        let result = cursor.seek(SeekFrom::End(1));
1574        result.expect_err("Should have failed to seek beyond end of data");
1575    }
1576
1577    #[test]
1578    fn test_cursor_seek_current_forward_twice() {
1579        let bytes = [0u8; 10];
1580        let mut cursor = Cursor::new(&bytes);
1581
1582        let result = cursor.seek(SeekFrom::Current(4));
1583        let position = result.expect("Seek should succeed");
1584        assert_eq!(position, 4, "Seek moved to the wrong position");
1585
1586        let result = cursor.seek(SeekFrom::Current(2));
1587        let position = result.expect("Seek should succeed");
1588        assert_eq!(position, 6, "Seek moved to the wrong position");
1589    }
1590
1591    #[test]
1592    fn test_cursor_seek_current_forward_backward() {
1593        let bytes = [0u8; 10];
1594        let mut cursor = Cursor::new(&bytes);
1595
1596        cursor.seek(SeekFrom::Current(4)).expect("Seek should succeed");
1597
1598        let result = cursor.seek(SeekFrom::Current(-2));
1599        let position = result.expect("Seek should succeed");
1600        assert_eq!(position, 2, "Seek moved to the wrong position");
1601    }
1602
1603    #[test]
1604    fn test_cursor_seek_current_forward_backward_fail_before_start() {
1605        let bytes = [0u8; 10];
1606        let mut cursor = Cursor::new(&bytes);
1607
1608        cursor.seek(SeekFrom::Current(4)).expect("Seek should succeed");
1609
1610        let result = cursor.seek(SeekFrom::Current(-5));
1611        result.expect_err("Should have failed to seek before start of data");
1612    }
1613
1614    #[test]
1615    fn test_cursor_seek_current_forward_twice_fail_beyond_end() {
1616        let bytes = [0u8; 10];
1617        let mut cursor = Cursor::new(&bytes);
1618
1619        cursor.seek(SeekFrom::Current(4)).expect("Seek should succeed");
1620
1621        let result = cursor.seek(SeekFrom::Current(7));
1622        result.expect_err("Should have failed to seek beyond end of data");
1623    }
1624
1625    #[test]
1626    fn test_owned_policy_serial_deserial_is_identity() {
1627        let op = OwnedPolicy {
1628            identity_provider: 1234,
1629            created_at:        Timestamp::from_timestamp_millis(11),
1630            valid_to:          Timestamp::from_timestamp_millis(999999),
1631            items:             vec![
1632                (attributes::COUNTRY_OF_RESIDENCE, b"DK".into()),
1633                (attributes::ID_DOC_TYPE, b"A document type with 31 chars..".into()),
1634            ],
1635        };
1636        let mut buf = Vec::new();
1637        op.serial(&mut buf).unwrap();
1638        let res = OwnedPolicy::deserial(&mut Cursor::new(buf)).unwrap();
1639        assert_eq!(op.identity_provider, res.identity_provider, "identity provider didn't match");
1640        assert_eq!(op.created_at, res.created_at, "created_at didn't match");
1641        assert_eq!(op.valid_to, res.valid_to, "valid_to didn't match");
1642        assert_eq!(op.items, res.items, "items didn't match");
1643    }
1644}