1use anyhow::{bail, ensure, Context};
2use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
3use concordium_contracts_common::{Duration, ExchangeRate};
4use core::cmp;
5use sha2::Digest;
6use std::{
7 collections::btree_map::BTreeMap,
8 convert::{TryFrom, TryInto},
9 marker::PhantomData,
10};
11
12static MAX_PREALLOCATED_CAPACITY: usize = 4096;
15
16pub type ParseResult<T> = anyhow::Result<T>;
19
20#[inline]
23pub fn safe_with_capacity<T>(capacity: usize) -> Vec<T> {
24 Vec::with_capacity(cmp::min(capacity, MAX_PREALLOCATED_CAPACITY))
28}
29
30pub trait Deserial: Sized {
32 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self>;
33}
34
35impl Deserial for u128 {
36 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u128> {
37 Ok(source.read_u128::<BigEndian>()?)
38 }
39}
40
41impl Deserial for u64 {
42 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u64> {
43 Ok(source.read_u64::<BigEndian>()?)
44 }
45}
46
47impl Deserial for u32 {
48 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u32> {
49 Ok(source.read_u32::<BigEndian>()?)
50 }
51}
52
53impl Deserial for u16 {
54 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u16> {
55 Ok(source.read_u16::<BigEndian>()?)
56 }
57}
58
59impl Deserial for bool {
60 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
61 let x: u8 = source.read_u8()?;
62 match x {
63 0 => Ok(false),
64 1 => Ok(true),
65 _ => anyhow::bail!("Unrecognized boolean value {}", x),
66 }
67 }
68}
69
70impl Deserial for u8 {
71 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u8> { Ok(source.read_u8()?) }
72}
73
74impl Deserial for i128 {
75 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i128> {
76 Ok(source.read_i128::<BigEndian>()?)
77 }
78}
79
80impl Deserial for i64 {
81 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i64> {
82 Ok(source.read_i64::<BigEndian>()?)
83 }
84}
85
86impl Deserial for i32 {
87 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i32> {
88 Ok(source.read_i32::<BigEndian>()?)
89 }
90}
91
92impl Deserial for i16 {
93 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i16> {
94 Ok(source.read_i16::<BigEndian>()?)
95 }
96}
97
98impl Deserial for i8 {
99 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i8> { Ok(source.read_i8()?) }
100}
101
102impl Deserial for std::num::NonZeroU8 {
103 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
104 let value = source.get()?;
105 Self::new(value).context("Zero is not valid.")
106 }
107}
108
109impl Deserial for std::num::NonZeroU16 {
110 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
111 let value = source.get()?;
112 Self::new(value).context("Zero is not valid.")
113 }
114}
115impl Deserial for std::num::NonZeroU32 {
116 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
117 let value = source.get()?;
118 Self::new(value).context("Zero is not valid.")
119 }
120}
121
122impl Deserial for std::num::NonZeroU64 {
123 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
124 let value = source.get()?;
125 Self::new(value).context("Zero is not valid.")
126 }
127}
128
129impl Deserial for std::num::NonZeroU128 {
130 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
131 let value = source.get()?;
132 Self::new(value).context("Zero is not valid.")
133 }
134}
135
136impl Deserial for std::num::NonZeroI8 {
137 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
138 let value = source.get()?;
139 Self::new(value).context("Zero is not valid.")
140 }
141}
142
143impl Deserial for std::num::NonZeroI16 {
144 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
145 let value = source.get()?;
146 Self::new(value).context("Zero is not valid.")
147 }
148}
149impl Deserial for std::num::NonZeroI32 {
150 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
151 let value = source.get()?;
152 Self::new(value).context("Zero is not valid.")
153 }
154}
155
156impl Deserial for std::num::NonZeroI64 {
157 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
158 let value = source.get()?;
159 Self::new(value).context("Zero is not valid.")
160 }
161}
162
163impl Deserial for std::num::NonZeroI128 {
164 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
165 let value = source.get()?;
166 Self::new(value).context("Zero is not valid.")
167 }
168}
169
170impl Deserial for num::rational::Ratio<u64> {
171 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
172 let numerator = source.get()?;
173 let denominator = source.get()?;
174 ensure!(denominator != 0, "Denominator of zero is not valid.");
175 Ok(Self::new_raw(numerator, denominator))
176 }
177}
178
179impl<T: Deserial> Deserial for Vec<T> {
181 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
182 let len: u64 = u64::deserial(source)?;
183 deserial_vector_no_length(source, usize::try_from(len)?)
184 }
185}
186
187impl<T: Deserial + std::cmp::Ord> Deserial for BTreeSet<T> {
190 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
191 let len: u64 = u64::deserial(source)?;
192 deserial_set_no_length(source, usize::try_from(len)?)
193 }
194}
195
196impl<K: Deserial + std::cmp::Ord, V: Deserial> Deserial for BTreeMap<K, V> {
199 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
200 let len: u64 = u64::deserial(source)?;
201 deserial_map_no_length(source, usize::try_from(len)?)
202 }
203}
204
205impl<T: Deserial, U: Deserial> Deserial for (T, U) {
206 #[inline]
207 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
208 let x = T::deserial(source)?;
209 let y = U::deserial(source)?;
210 Ok((x, y))
211 }
212}
213
214impl<T: Deserial, S: Deserial, U: Deserial> Deserial for (T, S, U) {
215 #[inline]
216 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
217 let x = T::deserial(source)?;
218 let y = S::deserial(source)?;
219 let z = U::deserial(source)?;
220 Ok((x, y, z))
221 }
222}
223
224pub fn deserial_string<R: ReadBytesExt>(reader: &mut R, l: usize) -> ParseResult<String> {
229 let mut svec = vec![0; l];
230 reader.read_exact(&mut svec)?;
231 Ok(String::from_utf8(svec)?)
232}
233
234pub fn serial_string<R: Buffer>(s: &str, out: &mut R) {
237 out.write_all(s.as_bytes())
238 .expect("Writing to buffer should succeed.")
239}
240
241pub fn deserial_vector_no_length<R: ReadBytesExt, T: Deserial>(
244 reader: &mut R,
245 len: usize,
246) -> ParseResult<Vec<T>> {
247 let mut vec = safe_with_capacity(len);
248 for _ in 0..len {
249 vec.push(T::deserial(reader)?);
250 }
251 Ok(vec)
252}
253
254pub fn deserial_bytes<R: ReadBytesExt>(reader: &mut R, l: usize) -> ParseResult<Vec<u8>> {
259 let mut svec = vec![0; l];
260 reader.read_exact(&mut svec)?;
261 Ok(svec)
262}
263
264impl<T> Deserial for PhantomData<T> {
265 #[inline]
266 fn deserial<R: ReadBytesExt>(_source: &mut R) -> ParseResult<Self> { Ok(Default::default()) }
267}
268
269impl<T: Deserial> Deserial for Box<T> {
270 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
271 let x = T::deserial(source)?;
272 Ok(Box::new(x))
273 }
274}
275
276pub trait Buffer: Sized + WriteBytesExt {
281 type Result;
282 fn start() -> Self;
283 fn start_hint(_l: usize) -> Self { Self::start() }
284 fn result(self) -> Self::Result;
285}
286
287impl Buffer for Vec<u8> {
288 type Result = Vec<u8>;
289
290 fn start() -> Vec<u8> { Vec::new() }
291
292 fn start_hint(l: usize) -> Vec<u8> { Vec::with_capacity(l) }
293
294 fn result(self) -> Self::Result { self }
295}
296
297impl Buffer for sha2::Sha256 {
298 type Result = [u8; 32];
299
300 fn start() -> Self { sha2::Sha256::new() }
301
302 fn result(self) -> Self::Result { self.finalize().into() }
303}
304
305impl Buffer for sha2::Sha512 {
306 type Result = [u8; 64];
307
308 fn start() -> Self { sha2::Sha512::new() }
309
310 fn result(self) -> Self::Result { self.finalize().into() }
311}
312
313pub trait Serial {
316 fn serial<B: Buffer>(&self, out: &mut B);
317}
318
319impl Serial for u64 {
320 fn serial<B: Buffer>(&self, out: &mut B) {
321 out.write_u64::<BigEndian>(*self)
322 .expect("Writing to a buffer should not fail.")
323 }
324}
325
326impl Serial for u32 {
327 fn serial<B: Buffer>(&self, out: &mut B) {
328 out.write_u32::<BigEndian>(*self)
329 .expect("Writing to a buffer should not fail.")
330 }
331}
332
333impl Serial for u16 {
334 fn serial<B: Buffer>(&self, out: &mut B) {
335 out.write_u16::<BigEndian>(*self)
336 .expect("Writing to a buffer should not fail.")
337 }
338}
339
340impl Serial for bool {
341 fn serial<B: Buffer>(&self, out: &mut B) {
342 (if *self {
343 out.write_u8(1)
344 } else {
345 out.write_u8(0)
346 })
347 .expect("Writing to a buffer should not fail.");
348 }
349}
350
351impl Serial for u8 {
352 fn serial<B: Buffer>(&self, out: &mut B) {
353 out.write_u8(*self)
354 .expect("Writing to a buffer should not fail.")
355 }
356}
357
358impl Serial for i64 {
359 fn serial<B: Buffer>(&self, out: &mut B) {
360 out.write_i64::<BigEndian>(*self)
361 .expect("Writing to a buffer should not fail.")
362 }
363}
364
365impl Serial for i32 {
366 fn serial<B: Buffer>(&self, out: &mut B) {
367 out.write_i32::<BigEndian>(*self)
368 .expect("Writing to a buffer should not fail.")
369 }
370}
371
372impl Serial for i16 {
373 fn serial<B: Buffer>(&self, out: &mut B) {
374 out.write_i16::<BigEndian>(*self)
375 .expect("Writing to a buffer should not fail.")
376 }
377}
378
379impl Serial for i8 {
380 fn serial<B: Buffer>(&self, out: &mut B) {
381 out.write_i8(*self)
382 .expect("Writing to a buffer should not fail.")
383 }
384}
385
386impl Serial for std::num::NonZeroU8 {
387 fn serial<B: Buffer>(&self, out: &mut B) {
388 out.write_u8(self.get())
389 .expect("Writing to a buffer should not fail.")
390 }
391}
392
393impl Serial for std::num::NonZeroU16 {
394 fn serial<B: Buffer>(&self, out: &mut B) {
395 out.write_u16::<BigEndian>(self.get())
396 .expect("Writing to a buffer should not fail.")
397 }
398}
399
400impl Serial for std::num::NonZeroU32 {
401 fn serial<B: Buffer>(&self, out: &mut B) {
402 out.write_u32::<BigEndian>(self.get())
403 .expect("Writing to a buffer should not fail.")
404 }
405}
406
407impl Serial for std::num::NonZeroU64 {
408 fn serial<B: Buffer>(&self, out: &mut B) {
409 out.write_u64::<BigEndian>(self.get())
410 .expect("Writing to a buffer should not fail.")
411 }
412}
413
414impl Serial for std::num::NonZeroU128 {
415 fn serial<B: Buffer>(&self, out: &mut B) {
416 out.write_u128::<BigEndian>(self.get())
417 .expect("Writing to a buffer should not fail.")
418 }
419}
420
421impl Serial for std::num::NonZeroI8 {
422 fn serial<B: Buffer>(&self, out: &mut B) {
423 out.write_i8(self.get())
424 .expect("Writing to a buffer should not fail.")
425 }
426}
427
428impl Serial for std::num::NonZeroI16 {
429 fn serial<B: Buffer>(&self, out: &mut B) {
430 out.write_i16::<BigEndian>(self.get())
431 .expect("Writing to a buffer should not fail.")
432 }
433}
434
435impl Serial for std::num::NonZeroI32 {
436 fn serial<B: Buffer>(&self, out: &mut B) {
437 out.write_i32::<BigEndian>(self.get())
438 .expect("Writing to a buffer should not fail.")
439 }
440}
441
442impl Serial for std::num::NonZeroI64 {
443 fn serial<B: Buffer>(&self, out: &mut B) {
444 out.write_i64::<BigEndian>(self.get())
445 .expect("Writing to a buffer should not fail.")
446 }
447}
448
449impl Serial for std::num::NonZeroI128 {
450 fn serial<B: Buffer>(&self, out: &mut B) {
451 out.write_i128::<BigEndian>(self.get())
452 .expect("Writing to a buffer should not fail.")
453 }
454}
455
456impl Serial for num::rational::Ratio<u64> {
457 fn serial<B: Buffer>(&self, out: &mut B) {
458 self.numer().serial(out);
459 self.denom().serial(out);
460 }
461}
462
463impl<T: Serial> Serial for Vec<T> {
466 fn serial<B: Buffer>(&self, out: &mut B) {
467 (self.len() as u64).serial(out);
468 serial_vector_no_length(self, out)
469 }
470}
471
472impl Serial for String {
475 fn serial<B: Buffer>(&self, out: &mut B) {
476 (self.len() as u64).serial(out);
477 out.write_all(self.as_bytes())
478 .expect("Writing to buffer succeeds.")
479 }
480}
481
482impl Deserial for String {
483 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
484 let len = u64::deserial(source)?;
485 if len as usize <= MAX_PREALLOCATED_CAPACITY {
486 let mut data = vec![0u8; len as usize];
487 source.read_exact(&mut data)?;
488 let s = String::from_utf8(data)?;
489 Ok(s)
490 } else {
491 let mut chunk = vec![0u8; MAX_PREALLOCATED_CAPACITY];
492 let mut data = Vec::new();
493 let mut remaining = len as usize;
494 while remaining > 0 {
495 let to_read = std::cmp::min(remaining, MAX_PREALLOCATED_CAPACITY);
496 source.read_exact(&mut chunk[..to_read])?;
497 data.extend_from_slice(&chunk[..to_read]);
498 remaining -= to_read;
499 }
500 let s = String::from_utf8(data)?;
501 Ok(s)
502 }
503 }
504}
505
506impl<T: Serial> Serial for &[T] {
509 fn serial<B: Buffer>(&self, out: &mut B) {
510 (self.len() as u64).serial(out);
511 serial_vector_no_length(self, out)
512 }
513}
514
515impl<V: Serial> Serial for BTreeSet<V> {
518 fn serial<B: Buffer>(&self, out: &mut B) {
519 (self.len() as u64).serial(out);
520 serial_set_no_length(self, out)
521 }
522}
523
524impl<K: Serial, V: Serial> Serial for BTreeMap<K, V> {
527 fn serial<B: Buffer>(&self, out: &mut B) {
528 (self.len() as u64).serial(out);
529 serial_map_no_length(self, out)
530 }
531}
532
533pub fn serial_iter<'a, B: Buffer, T: Serial + 'a, I: Iterator<Item = &'a T>>(xs: I, out: &mut B) {
535 for x in xs {
536 x.serial(out);
537 }
538}
539
540pub fn serial_vector_no_length<B: Buffer, T: Serial>(xs: &[T], out: &mut B) {
542 serial_iter(xs.iter(), out)
543}
544
545pub fn serial_map_no_length<B: Buffer, K: Serial, V: Serial>(map: &BTreeMap<K, V>, out: &mut B) {
547 for (k, v) in map.iter() {
548 out.put(k);
550 out.put(v);
551 }
552}
553
554pub fn deserial_map_no_length<R: ReadBytesExt, K: Deserial + Ord, V: Deserial>(
557 source: &mut R,
558 len: usize,
559) -> ParseResult<BTreeMap<K, V>> {
560 let mut out = BTreeMap::new();
561 let mut x = None;
562 for _ in 0..len {
563 let k = source.get()?;
564 let v = source.get()?;
565 if let Some((old_k, old_v)) = x.take() {
566 if k > old_k {
567 out.insert(old_k, old_v);
568 } else {
569 bail!("Keys not in order.")
570 }
571 }
572 x = Some((k, v));
573 }
574 if let Some((k, v)) = x {
575 out.insert(k, v);
576 }
577 Ok(out)
578}
579
580pub fn serial_set_no_length<B: Buffer, K: Serial>(map: &BTreeSet<K>, out: &mut B) {
582 for k in map.iter() {
583 out.put(k);
584 }
585}
586
587pub fn deserial_set_no_length<R: ReadBytesExt, K: Deserial + Ord>(
591 source: &mut R,
592 len: usize,
593) -> ParseResult<BTreeSet<K>> {
594 let mut out = BTreeSet::new();
595 let mut x = None;
596 for _ in 0..len {
597 let k = source.get()?;
598 if let Some(old_k) = x.take() {
599 if k > old_k {
600 out.insert(old_k);
601 } else {
602 bail!("Keys not in order.")
603 }
604 }
605 x = Some(k);
606 }
607 if let Some(k) = x {
608 out.insert(k);
609 }
610 Ok(out)
611}
612
613impl<T: Serial, S: Serial> Serial for (T, S) {
614 #[inline]
615 fn serial<B: Buffer>(&self, out: &mut B) {
616 self.0.serial(out);
617 self.1.serial(out);
618 }
619}
620
621impl<T: Serial, S: Serial, U: Serial> Serial for (T, S, U) {
622 #[inline]
623 fn serial<B: Buffer>(&self, out: &mut B) {
624 self.0.serial(out);
625 self.1.serial(out);
626 self.2.serial(out);
627 }
628}
629
630impl<T> Serial for PhantomData<T> {
631 #[inline]
632 fn serial<B: Buffer>(&self, _out: &mut B) {}
633}
634
635impl<T: Serial> Serial for Box<T> {
636 #[inline]
637 fn serial<B: Buffer>(&self, out: &mut B) { self.as_ref().serial(out) }
638}
639
640impl Serial for [u8] {
641 #[inline]
642 fn serial<B: Buffer>(&self, out: &mut B) {
643 out.write_all(self).expect("Writing to buffer is safe.");
644 }
645}
646
647pub trait Get<A> {
654 fn get(&mut self) -> ParseResult<A>;
655}
656
657impl<R: ReadBytesExt, A: Deserial> Get<A> for R {
658 #[inline]
659 fn get(&mut self) -> ParseResult<A> { A::deserial(self) }
660}
661
662pub trait Put<A> {
666 fn put(&mut self, _v: &A);
667}
668
669impl<R: Buffer, A: Serial> Put<A> for R {
670 #[inline]
671 fn put(&mut self, v: &A) { v.serial(self) }
672}
673
674pub trait Serialize: Serial + Deserial {}
676
677impl<A: Deserial + Serial> Serialize for A {}
680
681#[inline]
683pub fn to_bytes<A: Serial>(x: &A) -> Vec<u8> {
684 let mut buf = Vec::new();
685 buf.put(x);
686 buf
687}
688
689#[inline]
690pub fn from_bytes<A: Deserial, R: ReadBytesExt>(source: &mut R) -> ParseResult<A> {
693 A::deserial(source)
694}
695
696impl<T: Serial, const N: usize> Serial for [T; N] {
699 fn serial<B: Buffer>(&self, out: &mut B) {
700 for x in self.iter() {
701 x.serial(out);
702 }
703 }
704}
705
706impl<T: Deserial, const N: usize> Deserial for [T; N] {
707 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
708 let mut out_vec = Vec::with_capacity(N);
709 for _ in 0..N {
710 out_vec.push(T::deserial(source)?);
711 }
712 let out_array: [T; N] = out_vec.try_into().map_err(|_| ()).unwrap();
713 Ok(out_array)
714 }
715}
716
717use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
719
720impl Serial for Ipv4Addr {
721 fn serial<W: WriteBytesExt>(&self, target: &mut W) {
722 target.write_u8(4).expect("Writing to buffer is safe.");
723 target
724 .write_all(&self.octets())
725 .expect("Writing to buffer is safe.");
726 }
727}
728
729impl Deserial for Ipv4Addr {
730 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
731 let mut octects = [0u8; 4];
732 source.read_exact(&mut octects)?;
733 Ok(Ipv4Addr::from(octects))
734 }
735}
736
737impl Serial for Ipv6Addr {
738 fn serial<W: WriteBytesExt>(&self, target: &mut W) {
739 target.write_u8(6).expect("Writing to buffer is safe.");
740 target
741 .write_all(&self.octets())
742 .expect("Writing to buffer is safe.");
743 }
744}
745
746impl Deserial for Ipv6Addr {
747 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
748 let mut octets = [0u8; 16];
749 source.read_exact(&mut octets)?;
750 Ok(Ipv6Addr::from(octets))
751 }
752}
753
754impl Serial for IpAddr {
755 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
756 match self {
757 IpAddr::V4(ip4) => ip4.serial(target),
758 IpAddr::V6(ip6) => ip6.serial(target),
759 }
760 }
761}
762
763impl Deserial for IpAddr {
764 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
765 match source.read_u8()? {
766 4 => Ok(IpAddr::V4(Ipv4Addr::deserial(source)?)),
767 6 => Ok(IpAddr::V6(Ipv6Addr::deserial(source)?)),
768 x => bail!("Can't deserialize an IpAddr (unknown type: {})", x),
769 }
770 }
771}
772
773impl Serial for SocketAddr {
774 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
775 self.ip().serial(target);
776 self.port().serial(target);
777 }
778}
779
780impl Deserial for SocketAddr {
781 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
782 Ok(SocketAddr::new(
783 IpAddr::deserial(source)?,
784 u16::deserial(source)?,
785 ))
786 }
787}
788
789impl Serial for ExchangeRate {
790 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
791 self.numerator().serial(target);
792 self.denominator().serial(target);
793 }
794}
795
796impl Deserial for ExchangeRate {
797 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
798 let numerator = source.get()?;
799 let denominator = source.get()?;
800 Self::new(numerator, denominator).ok_or_else(|| anyhow::anyhow!("Invalid exchange rate."))
801 }
802}
803
804impl Serial for Duration {
805 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) { self.millis().serial(target); }
806}
807
808impl Deserial for Duration {
809 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
810 let milliseconds = source.get()?;
811 Ok(Self::from_millis(milliseconds))
812 }
813}
814
815use std::{
816 collections::{BTreeSet, HashSet},
817 hash::{BuildHasher, Hash},
818};
819
820impl<T: Serial + Eq + Hash, S: BuildHasher + Default> Serial for HashSet<T, S> {
821 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
822 (self.len() as u32).serial(target);
823 self.iter().for_each(|ref item| item.serial(target));
824 }
825}
826
827impl<T: Deserial + Eq + Hash, S: BuildHasher + Default> Deserial for HashSet<T, S> {
828 fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
829 let len = u32::deserial(source)?;
830 let mut out = HashSet::with_capacity_and_hasher(
831 std::cmp::min(len as usize, MAX_PREALLOCATED_CAPACITY),
832 Default::default(),
833 );
834
835 for _i in 0..len {
836 out.insert(T::deserial(source)?);
837 }
838 Ok(out)
839 }
840}
841
842impl<T: Serial> Serial for &T {
843 fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) { (*self).serial(target) }
844}
845
846use hex::{decode, encode};
849use serde::{de, de::Visitor, Deserializer, Serializer};
850use std::{fmt, io::Cursor};
851
852pub fn base16_encode<S: Serializer, T: Serial>(v: &T, ser: S) -> Result<S::Ok, S::Error> {
856 let b16_str = encode(to_bytes(v));
857 ser.serialize_str(&b16_str)
858}
859
860pub fn base16_decode<'de, D: Deserializer<'de>, T: Deserial>(des: D) -> Result<T, D::Error> {
862 struct Base16Visitor<D>(std::marker::PhantomData<D>);
863
864 impl<'de, D: Deserial> Visitor<'de> for Base16Visitor<D> {
865 type Value = D;
866
867 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
868 write!(formatter, "A base 16 string.")
869 }
870
871 fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
872 let bytes = decode(v).map_err(de::Error::custom)?;
873 D::deserial(&mut Cursor::new(&bytes)).map_err(de::Error::custom)
874 }
875 }
876
877 des.deserialize_str(Base16Visitor(Default::default()))
878}
879
880pub(crate) fn base16_encode_array<S: Serializer, const N: usize>(
883 v: &[u8; N],
884 ser: S,
885) -> Result<S::Ok, S::Error> {
886 let b16_str = encode(v);
887 ser.serialize_str(&b16_str)
888}
889
890pub(crate) fn base16_decode_array<'de, D: Deserializer<'de>, const N: usize>(
893 des: D,
894) -> Result<[u8; N], D::Error> {
895 struct Base16Visitor<const N: usize>(std::marker::PhantomData<[u8; N]>);
896
897 impl<'de, const N: usize> Visitor<'de> for Base16Visitor<N> {
898 type Value = [u8; N];
899
900 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
901 write!(formatter, "A base 16 string.")
902 }
903
904 fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
905 let bytes = decode(v).map_err(de::Error::custom)?;
906 bytes
907 .try_into()
908 .map_err(|_| de::Error::custom("Unexpected array length."))
909 }
910 }
911
912 des.deserialize_str(Base16Visitor(Default::default()))
913}
914
915pub fn base16_encode_string<S: Serial>(x: &S) -> String { encode(to_bytes(x)) }
918
919pub fn base16_decode_string<S: Deserial>(x: &str) -> ParseResult<S> {
921 let d = decode(x)?;
922 from_bytes(&mut Cursor::new(&d))
923}
924
925pub fn base16_ignore_length_encode<S: Serializer, T: Serial>(
931 v: &T,
932 ser: S,
933) -> Result<S::Ok, S::Error> {
934 let b16_str = encode(&to_bytes(v)[4..]);
935 ser.serialize_str(&b16_str)
936}
937
938pub fn base16_ignore_length_decode<'de, D: Deserializer<'de>, T: Deserial>(
940 des: D,
941) -> Result<T, D::Error> {
942 struct Base16IgnoreLengthVisitor<D>(std::marker::PhantomData<D>);
946
947 impl<'de, D: Deserial> Visitor<'de> for Base16IgnoreLengthVisitor<D> {
948 type Value = D;
949
950 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
951 write!(formatter, "A base 16 string.")
952 }
953
954 fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
955 let bytes = decode(v).map_err(de::Error::custom)?;
956 let mut all_bytes = Vec::with_capacity(bytes.len() + 4);
957 all_bytes.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
958 all_bytes.extend_from_slice(&bytes);
959 D::deserial(&mut Cursor::new(&all_bytes)).map_err(de::Error::custom)
960 }
961 }
962 des.deserialize_str(Base16IgnoreLengthVisitor(Default::default()))
963}
964
965#[test]
966fn test_map_serialization() {
967 use rand::Rng;
968 for n in 0..1000 {
969 let mut map = BTreeMap::<u64, u32>::new();
970 for (k, v) in rand::thread_rng()
971 .sample_iter(rand::distributions::Standard)
972 .take(n)
973 {
974 map.insert(k, v);
975 }
976 let deserialized = super::serialize_deserialize(&map).expect("Deserialization succeeds.");
977 assert_eq!(map, deserialized);
978 }
979}
980
981#[test]
982fn test_set_serialization() {
983 use rand::Rng;
984 for n in 0..1000 {
985 let mut set = BTreeSet::<u64>::new();
986 for k in rand::thread_rng()
987 .sample_iter(rand::distributions::Standard)
988 .take(n)
989 {
990 set.insert(k);
991 }
992 let deserialized = super::serialize_deserialize(&set).expect("Deserialization succeeds.");
993 assert_eq!(set, deserialized);
994 }
995}
996
997#[test]
998fn test_string_serialization() {
999 use rand::Rng;
1000 for _ in 0..1000 {
1001 let n: usize = rand::thread_rng().gen_range(0..2 * MAX_PREALLOCATED_CAPACITY);
1002 let s: String = String::from_utf8(vec!['a' as u8; n]).unwrap();
1003 let deserialized = super::serialize_deserialize(&s).expect("Deserialization succeeds.");
1004 assert_eq!(s, deserialized);
1005 }
1006}