1mod bytes;
3
4use alloc::{
5 boxed::Box,
6 collections::{BTreeMap, BTreeSet, VecDeque},
7 str,
8 string::String,
9 vec,
10 vec::Vec,
11};
12#[cfg(debug_assertions)]
13use core::any;
14use core::{
15 convert::TryInto,
16 fmt::{self, Display, Formatter},
17};
18#[cfg(feature = "std")]
19use std::error::Error as StdError;
20
21#[cfg(feature = "datasize")]
22use datasize::DataSize;
23use num_integer::Integer;
24use num_rational::Ratio;
25#[cfg(feature = "json-schema")]
26use schemars::JsonSchema;
27use serde::{Deserialize, Serialize};
28
29pub use bytes::Bytes;
30
31pub const UNIT_SERIALIZED_LENGTH: usize = 0;
33pub const BOOL_SERIALIZED_LENGTH: usize = 1;
35pub const I32_SERIALIZED_LENGTH: usize = size_of::<i32>();
37pub const I64_SERIALIZED_LENGTH: usize = size_of::<i64>();
39pub const U8_SERIALIZED_LENGTH: usize = size_of::<u8>();
41pub const U16_SERIALIZED_LENGTH: usize = size_of::<u16>();
43pub const U32_SERIALIZED_LENGTH: usize = size_of::<u32>();
45pub const U64_SERIALIZED_LENGTH: usize = size_of::<u64>();
47pub const U128_SERIALIZED_LENGTH: usize = size_of::<u128>();
49pub const U256_SERIALIZED_LENGTH: usize = U128_SERIALIZED_LENGTH * 2;
51pub const U512_SERIALIZED_LENGTH: usize = U256_SERIALIZED_LENGTH * 2;
53pub const OPTION_NONE_TAG: u8 = 0;
55pub const OPTION_SOME_TAG: u8 = 1;
57pub const RESULT_ERR_TAG: u8 = 0;
59pub const RESULT_OK_TAG: u8 = 1;
61
62pub trait ToBytes {
64 fn to_bytes(&self) -> Result<Vec<u8>, Error>;
66 fn into_bytes(self) -> Result<Vec<u8>, Error>
68 where
69 Self: Sized,
70 {
71 self.to_bytes()
72 }
73 fn serialized_length(&self) -> usize;
77
78 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
80 writer.extend(self.to_bytes()?);
81 Ok(())
82 }
83}
84
85pub trait FromBytes: Sized {
87 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>;
89
90 fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
92 Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
93 }
94}
95
96pub fn unchecked_allocate_buffer<T: ToBytes>(to_be_serialized: &T) -> Vec<u8> {
99 let serialized_length = to_be_serialized.serialized_length();
100 Vec::with_capacity(serialized_length)
101}
102
103pub fn allocate_buffer<T: ToBytes>(to_be_serialized: &T) -> Result<Vec<u8>, Error> {
106 let serialized_length = to_be_serialized.serialized_length();
107 allocate_buffer_for_size(serialized_length)
108}
109
110pub fn allocate_buffer_for_size(expected_size: usize) -> Result<Vec<u8>, Error> {
113 if expected_size > u32::MAX as usize {
114 return Err(Error::OutOfMemory);
115 }
116 Ok(Vec::with_capacity(expected_size))
117}
118
119#[derive(Copy, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
121#[cfg_attr(feature = "datasize", derive(DataSize))]
122#[cfg_attr(
123 feature = "json-schema",
124 derive(JsonSchema),
125 schemars(rename = "BytesreprError")
126)]
127#[cfg_attr(any(feature = "testing", test), derive(Default))]
129#[repr(u8)]
130#[non_exhaustive]
131pub enum Error {
132 #[cfg_attr(any(feature = "testing", test), default)]
134 EarlyEndOfStream = 0,
135 Formatting,
137 LeftOverBytes,
139 OutOfMemory,
141 NotRepresentable,
143 ExceededRecursionDepth,
145}
146
147impl Display for Error {
148 fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
149 match self {
150 Error::EarlyEndOfStream => {
151 formatter.write_str("Deserialization error: early end of stream")
152 }
153 Error::Formatting => formatter.write_str("Deserialization error: formatting"),
154 Error::LeftOverBytes => formatter.write_str("Deserialization error: left-over bytes"),
155 Error::OutOfMemory => formatter.write_str("Serialization error: out of memory"),
156 Error::NotRepresentable => {
157 formatter.write_str("Serialization error: value is not representable.")
158 }
159 Error::ExceededRecursionDepth => formatter.write_str("exceeded recursion depth"),
160 }
161 }
162}
163
164impl ToBytes for Error {
165 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
166 (*self as u8).to_bytes()
167 }
168
169 fn serialized_length(&self) -> usize {
170 U8_SERIALIZED_LENGTH
171 }
172
173 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
174 (*self as u8).write_bytes(writer)
175 }
176}
177
178impl FromBytes for Error {
179 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
180 let (value, remainder) = u8::from_bytes(bytes)?;
181 match value {
182 value if value == Error::EarlyEndOfStream as u8 => {
183 Ok((Error::EarlyEndOfStream, remainder))
184 }
185 value if value == Error::Formatting as u8 => Ok((Error::Formatting, remainder)),
186 value if value == Error::LeftOverBytes as u8 => Ok((Error::LeftOverBytes, remainder)),
187 value if value == Error::OutOfMemory as u8 => Ok((Error::OutOfMemory, remainder)),
188 value if value == Error::NotRepresentable as u8 => {
189 Ok((Error::NotRepresentable, remainder))
190 }
191 value if value == Error::ExceededRecursionDepth as u8 => {
192 Ok((Error::ExceededRecursionDepth, remainder))
193 }
194 _ => Err(Error::Formatting),
195 }
196 }
197}
198
199#[cfg(feature = "std")]
200impl StdError for Error {}
201
202pub fn deserialize<T: FromBytes>(bytes: Vec<u8>) -> Result<T, Error> {
207 let (t, remainder) = T::from_bytes(&bytes)?;
208 if remainder.is_empty() {
209 Ok(t)
210 } else {
211 Err(Error::LeftOverBytes)
212 }
213}
214
215pub fn deserialize_from_slice<I: AsRef<[u8]>, O: FromBytes>(bytes: I) -> Result<O, Error> {
220 let (t, remainder) = O::from_bytes(bytes.as_ref())?;
221 if remainder.is_empty() {
222 Ok(t)
223 } else {
224 Err(Error::LeftOverBytes)
225 }
226}
227
228pub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {
230 t.into_bytes()
231}
232
233pub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {
235 if n > bytes.len() {
236 Err(Error::EarlyEndOfStream)
237 } else {
238 Ok(bytes.split_at(n))
239 }
240}
241
242impl ToBytes for () {
243 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
244 Ok(Vec::new())
245 }
246
247 fn serialized_length(&self) -> usize {
248 UNIT_SERIALIZED_LENGTH
249 }
250}
251
252impl FromBytes for () {
253 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
254 Ok(((), bytes))
255 }
256}
257
258impl ToBytes for bool {
259 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
260 u8::from(*self).to_bytes()
261 }
262
263 fn serialized_length(&self) -> usize {
264 BOOL_SERIALIZED_LENGTH
265 }
266
267 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
268 writer.push(*self as u8);
269 Ok(())
270 }
271}
272
273impl FromBytes for bool {
274 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
275 match bytes.split_first() {
276 None => Err(Error::EarlyEndOfStream),
277 Some((byte, rem)) => match byte {
278 1 => Ok((true, rem)),
279 0 => Ok((false, rem)),
280 _ => Err(Error::Formatting),
281 },
282 }
283 }
284}
285
286impl ToBytes for u8 {
287 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
288 Ok(vec![*self])
289 }
290
291 fn serialized_length(&self) -> usize {
292 U8_SERIALIZED_LENGTH
293 }
294
295 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
296 writer.push(*self);
297 Ok(())
298 }
299}
300
301impl FromBytes for u8 {
302 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
303 match bytes.split_first() {
304 None => Err(Error::EarlyEndOfStream),
305 Some((byte, rem)) => Ok((*byte, rem)),
306 }
307 }
308}
309
310impl ToBytes for i32 {
311 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
312 Ok(self.to_le_bytes().to_vec())
313 }
314
315 fn serialized_length(&self) -> usize {
316 I32_SERIALIZED_LENGTH
317 }
318
319 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
320 writer.extend_from_slice(&self.to_le_bytes());
321 Ok(())
322 }
323}
324
325impl FromBytes for i32 {
326 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
327 let mut result = [0u8; I32_SERIALIZED_LENGTH];
328 let (bytes, remainder) = safe_split_at(bytes, I32_SERIALIZED_LENGTH)?;
329 result.copy_from_slice(bytes);
330 Ok((<i32>::from_le_bytes(result), remainder))
331 }
332}
333
334impl ToBytes for i64 {
335 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
336 Ok(self.to_le_bytes().to_vec())
337 }
338
339 fn serialized_length(&self) -> usize {
340 I64_SERIALIZED_LENGTH
341 }
342
343 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
344 writer.extend_from_slice(&self.to_le_bytes());
345 Ok(())
346 }
347}
348
349impl FromBytes for i64 {
350 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
351 let mut result = [0u8; I64_SERIALIZED_LENGTH];
352 let (bytes, remainder) = safe_split_at(bytes, I64_SERIALIZED_LENGTH)?;
353 result.copy_from_slice(bytes);
354 Ok((<i64>::from_le_bytes(result), remainder))
355 }
356}
357
358impl ToBytes for u16 {
359 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
360 Ok(self.to_le_bytes().to_vec())
361 }
362
363 fn serialized_length(&self) -> usize {
364 U16_SERIALIZED_LENGTH
365 }
366
367 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
368 writer.extend_from_slice(&self.to_le_bytes());
369 Ok(())
370 }
371}
372
373impl FromBytes for u16 {
374 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
375 let mut result = [0u8; U16_SERIALIZED_LENGTH];
376 let (bytes, remainder) = safe_split_at(bytes, U16_SERIALIZED_LENGTH)?;
377 result.copy_from_slice(bytes);
378 Ok((<u16>::from_le_bytes(result), remainder))
379 }
380}
381
382impl ToBytes for u32 {
383 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
384 Ok(self.to_le_bytes().to_vec())
385 }
386
387 fn serialized_length(&self) -> usize {
388 U32_SERIALIZED_LENGTH
389 }
390
391 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
392 writer.extend_from_slice(&self.to_le_bytes());
393 Ok(())
394 }
395}
396
397impl FromBytes for u32 {
398 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
399 let mut result = [0u8; U32_SERIALIZED_LENGTH];
400 let (bytes, remainder) = safe_split_at(bytes, U32_SERIALIZED_LENGTH)?;
401 result.copy_from_slice(bytes);
402 Ok((<u32>::from_le_bytes(result), remainder))
403 }
404}
405
406impl ToBytes for u64 {
407 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
408 Ok(self.to_le_bytes().to_vec())
409 }
410
411 fn serialized_length(&self) -> usize {
412 U64_SERIALIZED_LENGTH
413 }
414
415 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
416 writer.extend_from_slice(&self.to_le_bytes());
417 Ok(())
418 }
419}
420
421impl FromBytes for u64 {
422 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
423 let mut result = [0u8; U64_SERIALIZED_LENGTH];
424 let (bytes, remainder) = safe_split_at(bytes, U64_SERIALIZED_LENGTH)?;
425 result.copy_from_slice(bytes);
426 Ok((<u64>::from_le_bytes(result), remainder))
427 }
428}
429
430impl ToBytes for u128 {
431 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
432 Ok(self.to_le_bytes().to_vec())
433 }
434
435 fn serialized_length(&self) -> usize {
436 U128_SERIALIZED_LENGTH
437 }
438
439 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
440 writer.extend_from_slice(&self.to_le_bytes());
441 Ok(())
442 }
443}
444
445impl FromBytes for u128 {
446 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
447 let mut result = [0u8; U128_SERIALIZED_LENGTH];
448 let (bytes, remainder) = safe_split_at(bytes, U128_SERIALIZED_LENGTH)?;
449 result.copy_from_slice(bytes);
450 Ok((<u128>::from_le_bytes(result), remainder))
451 }
452}
453
454impl ToBytes for String {
455 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
456 let bytes = self.as_bytes();
457 u8_slice_to_bytes(bytes)
458 }
459
460 fn serialized_length(&self) -> usize {
461 u8_slice_serialized_length(self.as_bytes())
462 }
463
464 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
465 write_u8_slice(self.as_bytes(), writer)?;
466 Ok(())
467 }
468}
469
470impl FromBytes for String {
471 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
472 let (size, remainder) = u32::from_bytes(bytes)?;
473 let (str_bytes, remainder) = safe_split_at(remainder, size as usize)?;
474 let result = String::from_utf8(str_bytes.to_vec()).map_err(|_| Error::Formatting)?;
475 Ok((result, remainder))
476 }
477}
478
479fn ensure_efficient_serialization<T>() {
480 #[cfg(debug_assertions)]
481 debug_assert_ne!(
482 any::type_name::<T>(),
483 any::type_name::<u8>(),
484 "You should use `casper_types::bytesrepr::Bytes` newtype wrapper instead of `Vec<u8>` for efficiency"
485 );
486}
487
488fn iterator_serialized_length<'a, T: 'a + ToBytes>(ts: impl Iterator<Item = &'a T>) -> usize {
489 U32_SERIALIZED_LENGTH + ts.map(ToBytes::serialized_length).sum::<usize>()
490}
491
492impl<T: ToBytes> ToBytes for Vec<T> {
493 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
494 ensure_efficient_serialization::<T>();
495
496 let mut result = Vec::with_capacity(self.serialized_length());
497 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
498 result.append(&mut length_32.to_bytes()?);
499
500 for item in self.iter() {
501 result.append(&mut item.to_bytes()?);
502 }
503
504 Ok(result)
505 }
506
507 fn into_bytes(self) -> Result<Vec<u8>, Error> {
508 ensure_efficient_serialization::<T>();
509
510 let mut result = allocate_buffer(&self)?;
511 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
512 result.append(&mut length_32.to_bytes()?);
513
514 for item in self {
515 result.append(&mut item.into_bytes()?);
516 }
517
518 Ok(result)
519 }
520
521 fn serialized_length(&self) -> usize {
522 iterator_serialized_length(self.iter())
523 }
524
525 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
526 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
527 writer.extend_from_slice(&length_32.to_le_bytes());
528 for item in self.iter() {
529 item.write_bytes(writer)?;
530 }
531 Ok(())
532 }
533}
534
535fn vec_from_vec<T: FromBytes>(bytes: Vec<u8>) -> Result<(Vec<T>, Vec<u8>), Error> {
536 ensure_efficient_serialization::<T>();
537
538 Vec::<T>::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
539}
540
541#[inline]
546fn cautious<T>(hint: usize) -> usize {
547 let el_size = size_of::<T>();
548 core::cmp::max(core::cmp::min(hint, 4096 / el_size), 1)
549}
550
551impl<T: FromBytes> FromBytes for Vec<T> {
552 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
553 ensure_efficient_serialization::<T>();
554
555 let (count, mut stream) = u32::from_bytes(bytes)?;
556
557 if count == 0 {
558 return Ok((Vec::new(), stream));
559 }
560
561 let mut result = Vec::with_capacity(cautious::<T>(count as usize));
562
563 for _ in 0..count {
564 let (value, remainder) = T::from_bytes(stream)?;
565 result.push(value);
566 stream = remainder;
567 }
568
569 Ok((result, stream))
570 }
571
572 fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
573 vec_from_vec(bytes)
574 }
575}
576
577impl<T: ToBytes> ToBytes for VecDeque<T> {
578 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
579 let (slice1, slice2) = self.as_slices();
580 let mut result = allocate_buffer(self)?;
581 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
582 result.append(&mut length_32.to_bytes()?);
583 for item in slice1.iter().chain(slice2.iter()) {
584 result.append(&mut item.to_bytes()?);
585 }
586 Ok(result)
587 }
588
589 fn into_bytes(self) -> Result<Vec<u8>, Error> {
590 let vec: Vec<T> = self.into();
591 vec.to_bytes()
592 }
593
594 fn serialized_length(&self) -> usize {
595 let (slice1, slice2) = self.as_slices();
596 iterator_serialized_length(slice1.iter().chain(slice2.iter()))
597 }
598}
599
600impl<T: FromBytes> FromBytes for VecDeque<T> {
601 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
602 let (vec, bytes) = Vec::from_bytes(bytes)?;
603 Ok((VecDeque::from(vec), bytes))
604 }
605
606 fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
607 let (vec, bytes) = vec_from_vec(bytes)?;
608 Ok((VecDeque::from(vec), bytes))
609 }
610}
611
612impl<const COUNT: usize> ToBytes for [u8; COUNT] {
613 #[inline(always)]
614 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
615 Ok(self.to_vec())
616 }
617
618 #[inline(always)]
619 fn serialized_length(&self) -> usize {
620 COUNT
621 }
622
623 #[inline(always)]
624 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
625 writer.extend_from_slice(self);
626 Ok(())
627 }
628}
629
630impl<const COUNT: usize> FromBytes for [u8; COUNT] {
631 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
632 let (bytes, rem) = safe_split_at(bytes, COUNT)?;
633 let ptr = bytes.as_ptr() as *const [u8; COUNT];
635 let result = unsafe { *ptr };
636 Ok((result, rem))
637 }
638}
639
640impl<V: ToBytes> ToBytes for BTreeSet<V> {
641 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
642 let mut result = allocate_buffer(self)?;
643
644 let num_keys: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
645 result.append(&mut num_keys.to_bytes()?);
646
647 for value in self.iter() {
648 result.append(&mut value.to_bytes()?);
649 }
650
651 Ok(result)
652 }
653
654 fn serialized_length(&self) -> usize {
655 U32_SERIALIZED_LENGTH + self.iter().map(|v| v.serialized_length()).sum::<usize>()
656 }
657
658 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
659 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
660 writer.extend_from_slice(&length_32.to_le_bytes());
661 for value in self.iter() {
662 value.write_bytes(writer)?;
663 }
664 Ok(())
665 }
666}
667
668impl<V: FromBytes + Ord> FromBytes for BTreeSet<V> {
669 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
670 let (num_keys, mut stream) = u32::from_bytes(bytes)?;
671 let mut result = BTreeSet::new();
672 for _ in 0..num_keys {
673 let (v, rem) = V::from_bytes(stream)?;
674 result.insert(v);
675 stream = rem;
676 }
677 Ok((result, stream))
678 }
679}
680
681impl<K, V> ToBytes for BTreeMap<K, V>
682where
683 K: ToBytes,
684 V: ToBytes,
685{
686 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
687 let mut result = allocate_buffer(self)?;
688
689 let num_keys: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
690 result.append(&mut num_keys.to_bytes()?);
691
692 for (key, value) in self.iter() {
693 result.append(&mut key.to_bytes()?);
694 result.append(&mut value.to_bytes()?);
695 }
696
697 Ok(result)
698 }
699
700 fn serialized_length(&self) -> usize {
701 U32_SERIALIZED_LENGTH
702 + self
703 .iter()
704 .map(|(key, value)| key.serialized_length() + value.serialized_length())
705 .sum::<usize>()
706 }
707
708 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
709 let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
710 writer.extend_from_slice(&length_32.to_le_bytes());
711 for (key, value) in self.iter() {
712 key.write_bytes(writer)?;
713 value.write_bytes(writer)?;
714 }
715 Ok(())
716 }
717}
718
719impl<K, V> FromBytes for BTreeMap<K, V>
720where
721 K: FromBytes + Ord,
722 V: FromBytes,
723{
724 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
725 let (num_keys, mut stream) = u32::from_bytes(bytes)?;
726 let mut result = BTreeMap::new();
727 for _ in 0..num_keys {
728 let (k, rem) = K::from_bytes(stream)?;
729 let (v, rem) = V::from_bytes(rem)?;
730 result.insert(k, v);
731 stream = rem;
732 }
733 Ok((result, stream))
734 }
735}
736
737impl<T: ToBytes> ToBytes for Option<T> {
738 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
739 match self {
740 None => Ok(vec![OPTION_NONE_TAG]),
741 Some(v) => {
742 let mut result = allocate_buffer(self)?;
743 result.push(OPTION_SOME_TAG);
744
745 let mut value = v.to_bytes()?;
746 result.append(&mut value);
747
748 Ok(result)
749 }
750 }
751 }
752
753 fn serialized_length(&self) -> usize {
754 U8_SERIALIZED_LENGTH
755 + match self {
756 Some(v) => v.serialized_length(),
757 None => 0,
758 }
759 }
760
761 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
762 match self {
763 None => writer.push(OPTION_NONE_TAG),
764 Some(v) => {
765 writer.push(OPTION_SOME_TAG);
766 v.write_bytes(writer)?;
767 }
768 };
769 Ok(())
770 }
771}
772
773impl<T: FromBytes> FromBytes for Option<T> {
774 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
775 let (tag, rem) = u8::from_bytes(bytes)?;
776 match tag {
777 OPTION_NONE_TAG => Ok((None, rem)),
778 OPTION_SOME_TAG => {
779 let (t, rem) = T::from_bytes(rem)?;
780 Ok((Some(t), rem))
781 }
782 _ => Err(Error::Formatting),
783 }
784 }
785}
786
787impl<T: ToBytes, E: ToBytes> ToBytes for Result<T, E> {
788 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
789 let mut result = allocate_buffer(self)?;
790 let (variant, mut value) = match self {
791 Err(error) => (RESULT_ERR_TAG, error.to_bytes()?),
792 Ok(result) => (RESULT_OK_TAG, result.to_bytes()?),
793 };
794 result.push(variant);
795 result.append(&mut value);
796 Ok(result)
797 }
798
799 fn serialized_length(&self) -> usize {
800 U8_SERIALIZED_LENGTH
801 + match self {
802 Ok(ok) => ok.serialized_length(),
803 Err(error) => error.serialized_length(),
804 }
805 }
806
807 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
808 match self {
809 Err(error) => {
810 writer.push(RESULT_ERR_TAG);
811 error.write_bytes(writer)?;
812 }
813 Ok(result) => {
814 writer.push(RESULT_OK_TAG);
815 result.write_bytes(writer)?;
816 }
817 };
818 Ok(())
819 }
820}
821
822impl<T: FromBytes, E: FromBytes> FromBytes for Result<T, E> {
823 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
824 let (variant, rem) = u8::from_bytes(bytes)?;
825 match variant {
826 RESULT_ERR_TAG => {
827 let (value, rem) = E::from_bytes(rem)?;
828 Ok((Err(value), rem))
829 }
830 RESULT_OK_TAG => {
831 let (value, rem) = T::from_bytes(rem)?;
832 Ok((Ok(value), rem))
833 }
834 _ => Err(Error::Formatting),
835 }
836 }
837}
838
839impl<T1: ToBytes> ToBytes for (T1,) {
840 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
841 self.0.to_bytes()
842 }
843
844 fn serialized_length(&self) -> usize {
845 self.0.serialized_length()
846 }
847}
848
849impl<T1: FromBytes> FromBytes for (T1,) {
850 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
851 let (t1, remainder) = T1::from_bytes(bytes)?;
852 Ok(((t1,), remainder))
853 }
854}
855
856impl<T1: ToBytes, T2: ToBytes> ToBytes for (T1, T2) {
857 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
858 let mut result = allocate_buffer(self)?;
859 result.append(&mut self.0.to_bytes()?);
860 result.append(&mut self.1.to_bytes()?);
861 Ok(result)
862 }
863
864 fn serialized_length(&self) -> usize {
865 self.0.serialized_length() + self.1.serialized_length()
866 }
867}
868
869impl<T1: FromBytes, T2: FromBytes> FromBytes for (T1, T2) {
870 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
871 let (t1, remainder) = T1::from_bytes(bytes)?;
872 let (t2, remainder) = T2::from_bytes(remainder)?;
873 Ok(((t1, t2), remainder))
874 }
875}
876
877impl<T1: ToBytes, T2: ToBytes, T3: ToBytes> ToBytes for (T1, T2, T3) {
878 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
879 let mut result = allocate_buffer(self)?;
880 result.append(&mut self.0.to_bytes()?);
881 result.append(&mut self.1.to_bytes()?);
882 result.append(&mut self.2.to_bytes()?);
883 Ok(result)
884 }
885
886 fn serialized_length(&self) -> usize {
887 self.0.serialized_length() + self.1.serialized_length() + self.2.serialized_length()
888 }
889}
890
891impl<T1: FromBytes, T2: FromBytes, T3: FromBytes> FromBytes for (T1, T2, T3) {
892 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
893 let (t1, remainder) = T1::from_bytes(bytes)?;
894 let (t2, remainder) = T2::from_bytes(remainder)?;
895 let (t3, remainder) = T3::from_bytes(remainder)?;
896 Ok(((t1, t2, t3), remainder))
897 }
898}
899
900impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes> ToBytes for (T1, T2, T3, T4) {
901 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
902 let mut result = allocate_buffer(self)?;
903 result.append(&mut self.0.to_bytes()?);
904 result.append(&mut self.1.to_bytes()?);
905 result.append(&mut self.2.to_bytes()?);
906 result.append(&mut self.3.to_bytes()?);
907 Ok(result)
908 }
909
910 fn serialized_length(&self) -> usize {
911 self.0.serialized_length()
912 + self.1.serialized_length()
913 + self.2.serialized_length()
914 + self.3.serialized_length()
915 }
916}
917
918impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes> FromBytes for (T1, T2, T3, T4) {
919 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
920 let (t1, remainder) = T1::from_bytes(bytes)?;
921 let (t2, remainder) = T2::from_bytes(remainder)?;
922 let (t3, remainder) = T3::from_bytes(remainder)?;
923 let (t4, remainder) = T4::from_bytes(remainder)?;
924 Ok(((t1, t2, t3, t4), remainder))
925 }
926}
927
928impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes> ToBytes
929 for (T1, T2, T3, T4, T5)
930{
931 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
932 let mut result = allocate_buffer(self)?;
933 result.append(&mut self.0.to_bytes()?);
934 result.append(&mut self.1.to_bytes()?);
935 result.append(&mut self.2.to_bytes()?);
936 result.append(&mut self.3.to_bytes()?);
937 result.append(&mut self.4.to_bytes()?);
938 Ok(result)
939 }
940
941 fn serialized_length(&self) -> usize {
942 self.0.serialized_length()
943 + self.1.serialized_length()
944 + self.2.serialized_length()
945 + self.3.serialized_length()
946 + self.4.serialized_length()
947 }
948}
949
950impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes, T5: FromBytes> FromBytes
951 for (T1, T2, T3, T4, T5)
952{
953 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
954 let (t1, remainder) = T1::from_bytes(bytes)?;
955 let (t2, remainder) = T2::from_bytes(remainder)?;
956 let (t3, remainder) = T3::from_bytes(remainder)?;
957 let (t4, remainder) = T4::from_bytes(remainder)?;
958 let (t5, remainder) = T5::from_bytes(remainder)?;
959 Ok(((t1, t2, t3, t4, t5), remainder))
960 }
961}
962
963impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes, T6: ToBytes> ToBytes
964 for (T1, T2, T3, T4, T5, T6)
965{
966 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
967 let mut result = allocate_buffer(self)?;
968 result.append(&mut self.0.to_bytes()?);
969 result.append(&mut self.1.to_bytes()?);
970 result.append(&mut self.2.to_bytes()?);
971 result.append(&mut self.3.to_bytes()?);
972 result.append(&mut self.4.to_bytes()?);
973 result.append(&mut self.5.to_bytes()?);
974 Ok(result)
975 }
976
977 fn serialized_length(&self) -> usize {
978 self.0.serialized_length()
979 + self.1.serialized_length()
980 + self.2.serialized_length()
981 + self.3.serialized_length()
982 + self.4.serialized_length()
983 + self.5.serialized_length()
984 }
985}
986
987impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes, T5: FromBytes, T6: FromBytes>
988 FromBytes for (T1, T2, T3, T4, T5, T6)
989{
990 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
991 let (t1, remainder) = T1::from_bytes(bytes)?;
992 let (t2, remainder) = T2::from_bytes(remainder)?;
993 let (t3, remainder) = T3::from_bytes(remainder)?;
994 let (t4, remainder) = T4::from_bytes(remainder)?;
995 let (t5, remainder) = T5::from_bytes(remainder)?;
996 let (t6, remainder) = T6::from_bytes(remainder)?;
997 Ok(((t1, t2, t3, t4, t5, t6), remainder))
998 }
999}
1000
1001impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes, T6: ToBytes, T7: ToBytes>
1002 ToBytes for (T1, T2, T3, T4, T5, T6, T7)
1003{
1004 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1005 let mut result = allocate_buffer(self)?;
1006 result.append(&mut self.0.to_bytes()?);
1007 result.append(&mut self.1.to_bytes()?);
1008 result.append(&mut self.2.to_bytes()?);
1009 result.append(&mut self.3.to_bytes()?);
1010 result.append(&mut self.4.to_bytes()?);
1011 result.append(&mut self.5.to_bytes()?);
1012 result.append(&mut self.6.to_bytes()?);
1013 Ok(result)
1014 }
1015
1016 fn serialized_length(&self) -> usize {
1017 self.0.serialized_length()
1018 + self.1.serialized_length()
1019 + self.2.serialized_length()
1020 + self.3.serialized_length()
1021 + self.4.serialized_length()
1022 + self.5.serialized_length()
1023 + self.6.serialized_length()
1024 }
1025}
1026
1027impl<
1028 T1: FromBytes,
1029 T2: FromBytes,
1030 T3: FromBytes,
1031 T4: FromBytes,
1032 T5: FromBytes,
1033 T6: FromBytes,
1034 T7: FromBytes,
1035 > FromBytes for (T1, T2, T3, T4, T5, T6, T7)
1036{
1037 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1038 let (t1, remainder) = T1::from_bytes(bytes)?;
1039 let (t2, remainder) = T2::from_bytes(remainder)?;
1040 let (t3, remainder) = T3::from_bytes(remainder)?;
1041 let (t4, remainder) = T4::from_bytes(remainder)?;
1042 let (t5, remainder) = T5::from_bytes(remainder)?;
1043 let (t6, remainder) = T6::from_bytes(remainder)?;
1044 let (t7, remainder) = T7::from_bytes(remainder)?;
1045 Ok(((t1, t2, t3, t4, t5, t6, t7), remainder))
1046 }
1047}
1048
1049impl<
1050 T1: ToBytes,
1051 T2: ToBytes,
1052 T3: ToBytes,
1053 T4: ToBytes,
1054 T5: ToBytes,
1055 T6: ToBytes,
1056 T7: ToBytes,
1057 T8: ToBytes,
1058 > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8)
1059{
1060 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1061 let mut result = allocate_buffer(self)?;
1062 result.append(&mut self.0.to_bytes()?);
1063 result.append(&mut self.1.to_bytes()?);
1064 result.append(&mut self.2.to_bytes()?);
1065 result.append(&mut self.3.to_bytes()?);
1066 result.append(&mut self.4.to_bytes()?);
1067 result.append(&mut self.5.to_bytes()?);
1068 result.append(&mut self.6.to_bytes()?);
1069 result.append(&mut self.7.to_bytes()?);
1070 Ok(result)
1071 }
1072
1073 fn serialized_length(&self) -> usize {
1074 self.0.serialized_length()
1075 + self.1.serialized_length()
1076 + self.2.serialized_length()
1077 + self.3.serialized_length()
1078 + self.4.serialized_length()
1079 + self.5.serialized_length()
1080 + self.6.serialized_length()
1081 + self.7.serialized_length()
1082 }
1083}
1084
1085impl<
1086 T1: FromBytes,
1087 T2: FromBytes,
1088 T3: FromBytes,
1089 T4: FromBytes,
1090 T5: FromBytes,
1091 T6: FromBytes,
1092 T7: FromBytes,
1093 T8: FromBytes,
1094 > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8)
1095{
1096 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1097 let (t1, remainder) = T1::from_bytes(bytes)?;
1098 let (t2, remainder) = T2::from_bytes(remainder)?;
1099 let (t3, remainder) = T3::from_bytes(remainder)?;
1100 let (t4, remainder) = T4::from_bytes(remainder)?;
1101 let (t5, remainder) = T5::from_bytes(remainder)?;
1102 let (t6, remainder) = T6::from_bytes(remainder)?;
1103 let (t7, remainder) = T7::from_bytes(remainder)?;
1104 let (t8, remainder) = T8::from_bytes(remainder)?;
1105 Ok(((t1, t2, t3, t4, t5, t6, t7, t8), remainder))
1106 }
1107}
1108
1109impl<
1110 T1: ToBytes,
1111 T2: ToBytes,
1112 T3: ToBytes,
1113 T4: ToBytes,
1114 T5: ToBytes,
1115 T6: ToBytes,
1116 T7: ToBytes,
1117 T8: ToBytes,
1118 T9: ToBytes,
1119 > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9)
1120{
1121 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1122 let mut result = allocate_buffer(self)?;
1123 result.append(&mut self.0.to_bytes()?);
1124 result.append(&mut self.1.to_bytes()?);
1125 result.append(&mut self.2.to_bytes()?);
1126 result.append(&mut self.3.to_bytes()?);
1127 result.append(&mut self.4.to_bytes()?);
1128 result.append(&mut self.5.to_bytes()?);
1129 result.append(&mut self.6.to_bytes()?);
1130 result.append(&mut self.7.to_bytes()?);
1131 result.append(&mut self.8.to_bytes()?);
1132 Ok(result)
1133 }
1134
1135 fn serialized_length(&self) -> usize {
1136 self.0.serialized_length()
1137 + self.1.serialized_length()
1138 + self.2.serialized_length()
1139 + self.3.serialized_length()
1140 + self.4.serialized_length()
1141 + self.5.serialized_length()
1142 + self.6.serialized_length()
1143 + self.7.serialized_length()
1144 + self.8.serialized_length()
1145 }
1146}
1147
1148impl<
1149 T1: FromBytes,
1150 T2: FromBytes,
1151 T3: FromBytes,
1152 T4: FromBytes,
1153 T5: FromBytes,
1154 T6: FromBytes,
1155 T7: FromBytes,
1156 T8: FromBytes,
1157 T9: FromBytes,
1158 > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9)
1159{
1160 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1161 let (t1, remainder) = T1::from_bytes(bytes)?;
1162 let (t2, remainder) = T2::from_bytes(remainder)?;
1163 let (t3, remainder) = T3::from_bytes(remainder)?;
1164 let (t4, remainder) = T4::from_bytes(remainder)?;
1165 let (t5, remainder) = T5::from_bytes(remainder)?;
1166 let (t6, remainder) = T6::from_bytes(remainder)?;
1167 let (t7, remainder) = T7::from_bytes(remainder)?;
1168 let (t8, remainder) = T8::from_bytes(remainder)?;
1169 let (t9, remainder) = T9::from_bytes(remainder)?;
1170 Ok(((t1, t2, t3, t4, t5, t6, t7, t8, t9), remainder))
1171 }
1172}
1173
1174impl<
1175 T1: ToBytes,
1176 T2: ToBytes,
1177 T3: ToBytes,
1178 T4: ToBytes,
1179 T5: ToBytes,
1180 T6: ToBytes,
1181 T7: ToBytes,
1182 T8: ToBytes,
1183 T9: ToBytes,
1184 T10: ToBytes,
1185 > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)
1186{
1187 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1188 let mut result = allocate_buffer(self)?;
1189 result.append(&mut self.0.to_bytes()?);
1190 result.append(&mut self.1.to_bytes()?);
1191 result.append(&mut self.2.to_bytes()?);
1192 result.append(&mut self.3.to_bytes()?);
1193 result.append(&mut self.4.to_bytes()?);
1194 result.append(&mut self.5.to_bytes()?);
1195 result.append(&mut self.6.to_bytes()?);
1196 result.append(&mut self.7.to_bytes()?);
1197 result.append(&mut self.8.to_bytes()?);
1198 result.append(&mut self.9.to_bytes()?);
1199 Ok(result)
1200 }
1201
1202 fn serialized_length(&self) -> usize {
1203 self.0.serialized_length()
1204 + self.1.serialized_length()
1205 + self.2.serialized_length()
1206 + self.3.serialized_length()
1207 + self.4.serialized_length()
1208 + self.5.serialized_length()
1209 + self.6.serialized_length()
1210 + self.7.serialized_length()
1211 + self.8.serialized_length()
1212 + self.9.serialized_length()
1213 }
1214}
1215
1216impl<
1217 T1: FromBytes,
1218 T2: FromBytes,
1219 T3: FromBytes,
1220 T4: FromBytes,
1221 T5: FromBytes,
1222 T6: FromBytes,
1223 T7: FromBytes,
1224 T8: FromBytes,
1225 T9: FromBytes,
1226 T10: FromBytes,
1227 > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)
1228{
1229 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1230 let (t1, remainder) = T1::from_bytes(bytes)?;
1231 let (t2, remainder) = T2::from_bytes(remainder)?;
1232 let (t3, remainder) = T3::from_bytes(remainder)?;
1233 let (t4, remainder) = T4::from_bytes(remainder)?;
1234 let (t5, remainder) = T5::from_bytes(remainder)?;
1235 let (t6, remainder) = T6::from_bytes(remainder)?;
1236 let (t7, remainder) = T7::from_bytes(remainder)?;
1237 let (t8, remainder) = T8::from_bytes(remainder)?;
1238 let (t9, remainder) = T9::from_bytes(remainder)?;
1239 let (t10, remainder) = T10::from_bytes(remainder)?;
1240 Ok(((t1, t2, t3, t4, t5, t6, t7, t8, t9, t10), remainder))
1241 }
1242}
1243
1244impl ToBytes for str {
1245 #[inline]
1246 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1247 u8_slice_to_bytes(self.as_bytes())
1248 }
1249
1250 #[inline]
1251 fn serialized_length(&self) -> usize {
1252 u8_slice_serialized_length(self.as_bytes())
1253 }
1254
1255 #[inline]
1256 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
1257 write_u8_slice(self.as_bytes(), writer)?;
1258 Ok(())
1259 }
1260}
1261
1262impl ToBytes for &str {
1263 #[inline(always)]
1264 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1265 (*self).to_bytes()
1266 }
1267
1268 #[inline(always)]
1269 fn serialized_length(&self) -> usize {
1270 (*self).serialized_length()
1271 }
1272
1273 #[inline]
1274 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
1275 write_u8_slice(self.as_bytes(), writer)?;
1276 Ok(())
1277 }
1278}
1279
1280impl<T> ToBytes for &T
1281where
1282 T: ToBytes,
1283{
1284 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1285 (*self).to_bytes()
1286 }
1287
1288 fn serialized_length(&self) -> usize {
1289 (*self).serialized_length()
1290 }
1291}
1292
1293impl<T> ToBytes for Box<T>
1294where
1295 T: ToBytes,
1296{
1297 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1298 self.as_ref().to_bytes()
1299 }
1300
1301 fn serialized_length(&self) -> usize {
1302 self.as_ref().serialized_length()
1303 }
1304}
1305
1306impl<T> ToBytes for Ratio<T>
1307where
1308 T: Clone + Integer + ToBytes,
1309{
1310 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1311 if self.denom().is_zero() {
1312 return Err(Error::Formatting);
1313 }
1314 (self.numer().clone(), self.denom().clone()).into_bytes()
1315 }
1316
1317 fn serialized_length(&self) -> usize {
1318 (self.numer().clone(), self.denom().clone()).serialized_length()
1319 }
1320}
1321
1322impl<T> FromBytes for Ratio<T>
1323where
1324 T: Clone + FromBytes + Integer,
1325{
1326 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1327 let ((numer, denom), rem): ((T, T), &[u8]) = FromBytes::from_bytes(bytes)?;
1328 if denom.is_zero() {
1329 return Err(Error::Formatting);
1330 }
1331 Ok((Ratio::new(numer, denom), rem))
1332 }
1333}
1334
1335fn u8_slice_to_bytes(bytes: &[u8]) -> Result<Vec<u8>, Error> {
1342 let serialized_length = u8_slice_serialized_length(bytes);
1343 let mut vec = Vec::with_capacity(serialized_length);
1344 let length_prefix: u32 = bytes
1345 .len()
1346 .try_into()
1347 .map_err(|_| Error::NotRepresentable)?;
1348 let length_prefix_bytes = length_prefix.to_le_bytes();
1349 vec.extend_from_slice(&length_prefix_bytes);
1350 vec.extend_from_slice(bytes);
1351 Ok(vec)
1352}
1353
1354fn write_u8_slice(bytes: &[u8], writer: &mut Vec<u8>) -> Result<(), Error> {
1355 let length_32: u32 = bytes
1356 .len()
1357 .try_into()
1358 .map_err(|_| Error::NotRepresentable)?;
1359 writer.extend_from_slice(&length_32.to_le_bytes());
1360 writer.extend_from_slice(bytes);
1361 Ok(())
1362}
1363
1364#[allow(clippy::ptr_arg)]
1368#[inline]
1369pub(crate) fn vec_u8_to_bytes(vec: &Vec<u8>) -> Result<Vec<u8>, Error> {
1370 u8_slice_to_bytes(vec.as_slice())
1371}
1372
1373#[inline(always)]
1377fn u8_slice_serialized_length(bytes: &[u8]) -> usize {
1378 U32_SERIALIZED_LENGTH + bytes.len()
1379}
1380
1381#[allow(clippy::ptr_arg)]
1382#[inline]
1383pub(crate) fn vec_u8_serialized_length(vec: &Vec<u8>) -> usize {
1384 u8_slice_serialized_length(vec.as_slice())
1385}
1386
1387#[cfg(any(feature = "testing", test))]
1393#[track_caller]
1394pub fn test_serialization_roundtrip<T>(t: &T)
1395where
1396 T: fmt::Debug + ToBytes + FromBytes + PartialEq,
1397{
1398 let serialized = ToBytes::to_bytes(t).expect("Unable to serialize data");
1399 assert_eq!(
1400 serialized.len(),
1401 t.serialized_length(),
1402 "\nLength of serialized data: {},\nserialized_length() yielded: {},\n t is {:?}",
1403 serialized.len(),
1404 t.serialized_length(),
1405 t
1406 );
1407 let mut written_bytes = vec![];
1408 t.write_bytes(&mut written_bytes)
1409 .expect("Unable to serialize data via write_bytes");
1410 assert_eq!(serialized, written_bytes);
1411
1412 let deserialized_from_slice = deserialize_from_slice(&serialized)
1413 .unwrap_or_else(|error| panic!("Unable to deserialize data: {error:?} ({t:?})"));
1414 assert_eq!(*t, deserialized_from_slice);
1415
1416 let deserialized = deserialize::<T>(serialized).expect("Unable to deserialize data");
1417 assert_eq!(*t, deserialized);
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422 use crate::U128;
1423
1424 use super::*;
1425
1426 #[test]
1427 fn should_not_serialize_zero_denominator() {
1428 let malicious = Ratio::new_raw(1, 0);
1429 assert_eq!(malicious.to_bytes().unwrap_err(), Error::Formatting);
1430 }
1431
1432 #[test]
1433 fn should_not_deserialize_zero_denominator() {
1434 let malicious_bytes = (1u64, 0u64).to_bytes().unwrap();
1435 let result: Result<Ratio<u64>, Error> = deserialize(malicious_bytes);
1436 assert_eq!(result.unwrap_err(), Error::Formatting);
1437 }
1438
1439 #[test]
1440 fn should_have_generic_tobytes_impl_for_borrowed_types() {
1441 struct NonCopyable;
1442
1443 impl ToBytes for NonCopyable {
1444 fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1445 Ok(vec![1, 2, 3])
1446 }
1447
1448 fn serialized_length(&self) -> usize {
1449 3
1450 }
1451 }
1452
1453 let noncopyable: &NonCopyable = &NonCopyable;
1454
1455 assert_eq!(noncopyable.to_bytes().unwrap(), vec![1, 2, 3]);
1456 assert_eq!(noncopyable.serialized_length(), 3);
1457 assert_eq!(noncopyable.into_bytes().unwrap(), vec![1, 2, 3]);
1458 }
1459
1460 #[cfg(debug_assertions)]
1461 #[test]
1462 #[should_panic(
1463 expected = "You should use `casper_types::bytesrepr::Bytes` newtype wrapper instead of `Vec<u8>` for efficiency"
1464 )]
1465 fn should_fail_to_serialize_slice_of_u8() {
1466 let bytes = b"0123456789".to_vec();
1467 bytes.to_bytes().unwrap();
1468 }
1469
1470 #[test]
1471 fn should_calculate_capacity() {
1472 #[allow(dead_code)]
1473 struct CustomStruct {
1474 u8_field: u8,
1475 u16_field: u16,
1476 u32_field: u32,
1477 u64_field: u64,
1478 u128_field: U128,
1485 str_field: String,
1486 }
1487 assert_eq!(
1488 cautious::<usize>(u32::MAX as usize),
1489 512,
1490 "hint is 2^32-1 and we can only preallocate 512 elements"
1491 );
1492 assert_eq!(
1493 cautious::<u8>(usize::MAX),
1494 4096,
1495 "hint is usize::MAX and we can only preallocate 4096 elements"
1496 );
1497 assert_eq!(
1498 cautious::<u16>(usize::MAX),
1499 2048,
1500 "hint is usize::MAX and we can only preallocate 2048 elements"
1501 );
1502 assert_eq!(
1503 cautious::<CustomStruct>(usize::MAX),
1504 73,
1505 "hint is usize::MAX and we can only preallocate 73 elements"
1506 );
1507 }
1508
1509 #[test]
1510 fn deserializing_empty_vec_has_no_capacity() {
1511 let bytes = ToBytes::to_bytes(&(0u32, b"123")).unwrap();
1512 let (vec, rem): (Vec<u32>, _) = FromBytes::from_bytes(&bytes).unwrap();
1513 assert!(vec.is_empty());
1514 assert_eq!(vec.capacity(), 0);
1515 assert_eq!(rem, b"123");
1516 }
1517}
1518
1519#[cfg(test)]
1520mod proptests {
1521 use std::collections::VecDeque;
1522
1523 use proptest::{collection::vec, prelude::*};
1524
1525 use crate::{
1526 bytesrepr::{self, bytes::gens::bytes_arb, ToBytes},
1527 gens::*,
1528 };
1529
1530 proptest! {
1531 #[test]
1532 fn test_bool(u in any::<bool>()) {
1533 bytesrepr::test_serialization_roundtrip(&u);
1534 }
1535
1536 #[test]
1537 fn test_u8(u in any::<u8>()) {
1538 bytesrepr::test_serialization_roundtrip(&u);
1539 }
1540
1541 #[test]
1542 fn test_u16(u in any::<u16>()) {
1543 bytesrepr::test_serialization_roundtrip(&u);
1544 }
1545
1546 #[test]
1547 fn test_u32(u in any::<u32>()) {
1548 bytesrepr::test_serialization_roundtrip(&u);
1549 }
1550
1551 #[test]
1552 fn test_i32(u in any::<i32>()) {
1553 bytesrepr::test_serialization_roundtrip(&u);
1554 }
1555
1556 #[test]
1557 fn test_u64(u in any::<u64>()) {
1558 bytesrepr::test_serialization_roundtrip(&u);
1559 }
1560
1561 #[test]
1562 fn test_i64(u in any::<i64>()) {
1563 bytesrepr::test_serialization_roundtrip(&u);
1564 }
1565
1566 #[test]
1567 fn test_u8_slice_32(s in u8_slice_32()) {
1568 bytesrepr::test_serialization_roundtrip(&s);
1569 }
1570
1571 #[test]
1572 fn test_vec_u8(u in bytes_arb(1..100)) {
1573 bytesrepr::test_serialization_roundtrip(&u);
1574 }
1575
1576 #[test]
1577 fn test_vec_i32(u in vec(any::<i32>(), 1..100)) {
1578 bytesrepr::test_serialization_roundtrip(&u);
1579 }
1580
1581 #[test]
1582 fn test_vecdeque_i32((front, back) in (vec(any::<i32>(), 1..100), vec(any::<i32>(), 1..100))) {
1583 let mut vec_deque = VecDeque::new();
1584 for f in front {
1585 vec_deque.push_front(f);
1586 }
1587 for f in back {
1588 vec_deque.push_back(f);
1589 }
1590 bytesrepr::test_serialization_roundtrip(&vec_deque);
1591 }
1592
1593 #[test]
1594 fn test_vec_vec_u8(u in vec(bytes_arb(1..100), 10)) {
1595 bytesrepr::test_serialization_roundtrip(&u);
1596 }
1597
1598 #[test]
1599 fn test_uref_map(m in named_keys_arb(20)) {
1600 bytesrepr::test_serialization_roundtrip(&m);
1601 }
1602
1603 #[test]
1604 fn test_array_u8_32(arr in any::<[u8; 32]>()) {
1605 bytesrepr::test_serialization_roundtrip(&arr);
1606 }
1607
1608 #[test]
1609 fn test_string(s in "\\PC*") {
1610 bytesrepr::test_serialization_roundtrip(&s);
1611 }
1612
1613 #[test]
1614 fn test_str(s in "\\PC*") {
1615 let not_a_string_object = s.as_str();
1616 not_a_string_object.to_bytes().expect("should serialize a str");
1617 }
1618
1619 #[test]
1620 fn test_option(o in proptest::option::of(key_arb())) {
1621 bytesrepr::test_serialization_roundtrip(&o);
1622 }
1623
1624 #[test]
1625 fn test_unit(unit in Just(())) {
1626 bytesrepr::test_serialization_roundtrip(&unit);
1627 }
1628
1629 #[test]
1630 fn test_u128_serialization(u in u128_arb()) {
1631 bytesrepr::test_serialization_roundtrip(&u);
1632 }
1633
1634 #[test]
1635 fn test_u256_serialization(u in u256_arb()) {
1636 bytesrepr::test_serialization_roundtrip(&u);
1637 }
1638
1639 #[test]
1640 fn test_u512_serialization(u in u512_arb()) {
1641 bytesrepr::test_serialization_roundtrip(&u);
1642 }
1643
1644 #[test]
1645 fn test_key_serialization(key in key_arb()) {
1646 bytesrepr::test_serialization_roundtrip(&key);
1647 }
1648
1649 #[test]
1650 fn test_cl_value_serialization(cl_value in cl_value_arb()) {
1651 bytesrepr::test_serialization_roundtrip(&cl_value);
1652 }
1653
1654 #[test]
1655 fn test_access_rights(access_right in access_rights_arb()) {
1656 bytesrepr::test_serialization_roundtrip(&access_right);
1657 }
1658
1659 #[test]
1660 fn test_uref(uref in uref_arb()) {
1661 bytesrepr::test_serialization_roundtrip(&uref);
1662 }
1663
1664 #[test]
1665 fn test_account_hash(pk in account_hash_arb()) {
1666 bytesrepr::test_serialization_roundtrip(&pk);
1667 }
1668
1669 #[test]
1670 fn test_result(result in result_arb()) {
1671 bytesrepr::test_serialization_roundtrip(&result);
1672 }
1673
1674 #[test]
1675 fn test_phase_serialization(phase in phase_arb()) {
1676 bytesrepr::test_serialization_roundtrip(&phase);
1677 }
1678
1679 #[test]
1680 fn test_protocol_version(protocol_version in protocol_version_arb()) {
1681 bytesrepr::test_serialization_roundtrip(&protocol_version);
1682 }
1683
1684 #[test]
1685 fn test_sem_ver(sem_ver in sem_ver_arb()) {
1686 bytesrepr::test_serialization_roundtrip(&sem_ver);
1687 }
1688
1689 #[test]
1690 fn test_tuple1(t in (any::<u8>(),)) {
1691 bytesrepr::test_serialization_roundtrip(&t);
1692 }
1693
1694 #[test]
1695 fn test_tuple2(t in (any::<u8>(),any::<u32>())) {
1696 bytesrepr::test_serialization_roundtrip(&t);
1697 }
1698
1699 #[test]
1700 fn test_tuple3(t in (any::<u8>(),any::<u32>(),any::<i32>())) {
1701 bytesrepr::test_serialization_roundtrip(&t);
1702 }
1703
1704 #[test]
1705 fn test_tuple4(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>())) {
1706 bytesrepr::test_serialization_roundtrip(&t);
1707 }
1708 #[test]
1709 fn test_tuple5(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>())) {
1710 bytesrepr::test_serialization_roundtrip(&t);
1711 }
1712 #[test]
1713 fn test_tuple6(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1714 bytesrepr::test_serialization_roundtrip(&t);
1715 }
1716 #[test]
1717 fn test_tuple7(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1718 bytesrepr::test_serialization_roundtrip(&t);
1719 }
1720 #[test]
1721 fn test_tuple8(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1722 bytesrepr::test_serialization_roundtrip(&t);
1723 }
1724 #[test]
1725 fn test_tuple9(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1726 bytesrepr::test_serialization_roundtrip(&t);
1727 }
1728 #[test]
1729 fn test_tuple10(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1730 bytesrepr::test_serialization_roundtrip(&t);
1731 }
1732 #[test]
1733 fn test_ratio_u64(t in (any::<u64>(), 1..u64::MAX)) {
1734 bytesrepr::test_serialization_roundtrip(&t);
1735 }
1736 }
1737}