binary_sv2/datatypes/mod.rs
1// Provides implementations for encoding and decoding data types in the SV2 protocol,
2// supporting both fixed-size and dynamically-sized types. Defines the `Sv2DataType` trait,
3// which standardizes serialization and deserialization across various types, including
4// those with custom requirements like byte padding and dynamic sizing.
5//
6// ## Structure and Contents
7//
8// ### `Sv2DataType` Trait
9// The `Sv2DataType` trait offers methods to:
10// - **Deserialize**: Convert byte slices or reader sources into Rust types.
11// - **Serialize**: Encode Rust types into byte slices or write them to I/O streams.
12//
13// Supports both **checked** and **unchecked** variants for serialization and deserialization.
14// Checked functions validate data lengths, while unchecked versions assume size correctness for
15// optimized performance.
16//
17// ### Modules
18// - **`copy_data_types`**: Defines fixed-size types directly copied into or from byte slices, such
19// as `U24` (24-bit unsigned integer).
20// - **`non_copy_data_types`**: Manages dynamically-sized types, like sequences, public keys, and
21// strings, requiring size handling logic for SV2 compatibility.
22//
23// ### Re-exports
24// Re-exports common data types used in SV2 serialization, such as `PubKey`, `Signature`, `Seq0255`,
25// and others, simplifying protocol data handling with concrete implementations of `Sv2DataType`.
26//
27// The `Sv2DataType` trait and its implementations enable seamless conversion between in-memory
28// representations and serialized forms, ensuring efficient protocol communication and
29// interoperability.
30
31use crate::{
32 codec::{GetSize, SizeHint},
33 Error,
34};
35mod non_copy_data_types;
36
37mod copy_data_types;
38use crate::codec::decodable::FieldMarker;
39pub use copy_data_types::U24;
40pub use non_copy_data_types::{
41 Inner, PubKey, Seq0255, Seq064K, Signature, Str0255, Sv2Option, U32AsRef, B016M, B0255, B032,
42 B064K, U256,
43};
44
45use alloc::vec::Vec;
46use core::convert::TryInto;
47#[cfg(not(feature = "no_std"))]
48use std::io::{Error as E, Read, Write};
49
50/// `Sv2DataType` is a trait that defines methods for encoding and decoding Stratum V2 data.
51/// It is used for serializing and deserializing both fixed-size and dynamically-sized types.
52///
53/// Key Responsibilities:
54/// - Serialization: Converting data from in-memory representations to byte slices or streams.
55/// - Deserialization: Converting byte slices or streams back into the in-memory representation of
56/// the data.
57///
58/// This trait includes functions for both checked and unchecked conversions, providing flexibility
59/// in situations where error handling can be safely ignored.
60pub trait Sv2DataType<'a>: Sized + SizeHint + GetSize + TryInto<FieldMarker> {
61 /// Creates an instance of the type from a mutable byte slice, checking for size constraints.
62 ///
63 /// This function verifies that the provided byte slice has the correct size according to the
64 /// type's size hint.
65 fn from_bytes_(data: &'a mut [u8]) -> Result<Self, Error> {
66 Self::size_hint(data, 0)?;
67 Ok(Self::from_bytes_unchecked(data))
68 }
69
70 /// Constructs an instance from a mutable byte slice without verifying size constraints.
71 fn from_bytes_unchecked(data: &'a mut [u8]) -> Self;
72
73 /// Constructs an instance from a vector, checking for the correct size.
74 fn from_vec_(data: Vec<u8>) -> Result<Self, Error>;
75
76 /// Constructs an instance from a vector without validating its size.
77 fn from_vec_unchecked(data: Vec<u8>) -> Self;
78
79 // Constructs an instance from a reader source, checking for size constraints.
80 #[cfg(not(feature = "no_std"))]
81 fn from_reader_(reader: &mut impl Read) -> Result<Self, Error>;
82
83 /// Serializes the instance to a mutable slice, checking the destination size.
84 fn to_slice(&'a self, dst: &mut [u8]) -> Result<usize, Error> {
85 if dst.len() >= self.get_size() {
86 self.to_slice_unchecked(dst);
87 Ok(self.get_size())
88 } else {
89 Err(Error::WriteError(self.get_size(), dst.len()))
90 }
91 }
92
93 /// Serializes the instance to a mutable slice without checking the destination size.
94 fn to_slice_unchecked(&'a self, dst: &mut [u8]);
95
96 // Serializes the instance to a writer destination, checking for I/O errors.
97 #[cfg(not(feature = "no_std"))]
98 fn to_writer_(&self, writer: &mut impl Write) -> Result<(), E>;
99}