#![doc = include_str!("../README.md")]
use std::io;
use bincode::Options;
#[cfg(test)]
mod tests;
mod duplex;
mod read;
mod write;
pub use duplex::*;
pub use read::*;
pub use write::*;
pub(crate) const U16_MARKER: u8 = 252;
pub(crate) const U32_MARKER: u8 = 253;
pub(crate) const U64_MARKER: u8 = 254;
pub(crate) const ZST_MARKER: u8 = 255;
pub(crate) const CHECKSUM_ENABLED: u8 = 2;
pub(crate) const CHECKSUM_DISABLED: u8 = 3;
pub(crate) const PROTOCOL_VERSION: u64 = 2;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io error {0}")]
Io(#[from] io::Error),
#[error("bincode serialization/deserialization error {0}")]
Bincode(#[from] bincode::Error),
#[error("message sent exceeded configured length limit")]
SentMessageTooLarge,
#[error("message received exceeded configured length limit, terminating connection")]
ReceivedMessageTooLarge,
#[error("checksum mismatch, data corrupted or there was a protocol mismatch")]
ChecksumMismatch {
sent_checksum: u64,
computed_checksum: u64,
},
#[error("the peer is using an incompatible protocol version. Our version {our_version}, Their version {their_version}")]
ProtocolVersionMismatch {
our_version: u64,
their_version: u64,
},
#[error("checksum handshake failed, expected {CHECKSUM_ENABLED} or {CHECKSUM_DISABLED}, got {checksum_value}")]
ChecksumHandshakeFailed { checksum_value: u8 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChecksumEnabled {
Yes,
No,
}
impl From<bool> for ChecksumEnabled {
fn from(value: bool) -> Self {
if value {
ChecksumEnabled::Yes
} else {
ChecksumEnabled::No
}
}
}
impl From<ChecksumEnabled> for bool {
fn from(value: ChecksumEnabled) -> Self {
value == ChecksumEnabled::Yes
}
}
impl From<ChecksumEnabled> for ChecksumReadState {
fn from(value: ChecksumEnabled) -> Self {
match value {
ChecksumEnabled::Yes => ChecksumReadState::Yes,
ChecksumEnabled::No => ChecksumReadState::No,
}
}
}
fn bincode_options(size_limit: u64) -> impl Options {
bincode::DefaultOptions::new()
.with_limit(size_limit)
.with_little_endian()
.with_varint_encoding()
.reject_trailing_bytes()
}