#![cfg_attr(
feature = "std",
doc = "[`IoEncoder`]: crate::IoEncoder\n\
[`IoDecoder`]: crate::IoDecoder\n\
[`encode_into`]: crate::encode_into\n\
[`decode_from`]: crate::decode_from\n\
[`io`]: crate::io\n\
[`std::error::Error`]: std::error::Error"
)]
#![cfg_attr(
not(feature = "std"),
doc = "[`IoEncoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoEncoder.html\n\
[`IoDecoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoDecoder.html\n\
[`encode_into`]: https://docs.rs/pack-io/2/pack_io/fn.encode_into.html\n\
[`decode_from`]: https://docs.rs/pack-io/2/pack_io/fn.decode_from.html\n\
[`io`]: https://docs.rs/pack-io/2/pack_io/io/index.html\n\
[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html"
)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
#![deny(unused_must_use)]
#![deny(unused_results)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![deny(clippy::todo)]
#![deny(clippy::unimplemented)]
#![deny(clippy::print_stdout)]
#![deny(clippy::print_stderr)]
#![deny(clippy::dbg_macro)]
#![deny(clippy::unreachable)]
#![deny(clippy::undocumented_unsafe_blocks)]
#![forbid(unsafe_code)]
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "bytes")]
mod bytes_impls;
mod codec;
mod error;
mod impls;
#[cfg(feature = "std")]
pub mod io;
#[cfg(feature = "serde")]
pub mod serde;
mod traits;
mod varint;
mod view;
pub use crate::codec::{
Config, Decode, Decoder, Encode, Encoder, decode, decode_with_config, encode, peek_version,
varint_len,
};
pub use crate::error::{Result, SerialError};
pub use crate::traits::{Deserialize, Serialize};
pub use crate::view::{DeserializeView, decode_view, decode_view_with_config};
#[cfg(feature = "std")]
pub use crate::io::{IoDecoder, IoEncoder, decode_from, decode_from_with_config, encode_into};
#[cfg(feature = "derive")]
pub use pack_io_derive::{Deserialize, DeserializeView, Serialize};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[doc(hidden)]
pub mod __private {
use crate::codec::{Config, Decode, Decoder, Encode, Encoder};
use crate::error::{Result, SerialError};
pub use crate::codec::SizeCounter;
pub struct Fwd<'a, E: Encode + ?Sized>(pub &'a mut E);
impl<E: Encode + ?Sized> core::fmt::Debug for Fwd<'_, E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Fwd")
}
}
impl<E: Encode + ?Sized> Encode for Fwd<'_, E> {
#[inline]
fn write_byte(&mut self, byte: u8) -> Result<()> {
self.0.write_byte(byte)
}
#[inline]
fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
self.0.write_bytes(bytes)
}
#[inline]
fn reserve(&mut self, additional: usize) {
self.0.reserve(additional);
}
#[inline]
fn write_varint_u64(&mut self, value: u64) -> Result<()> {
self.0.write_varint_u64(value)
}
#[inline]
fn write_varint_u128(&mut self, value: u128) -> Result<()> {
self.0.write_varint_u128(value)
}
}
pub struct Tally<'a> {
inner: &'a mut dyn Encode,
written: usize,
}
impl<'a> Tally<'a> {
#[inline]
pub fn new(inner: &'a mut dyn Encode) -> Self {
Self { inner, written: 0 }
}
#[inline]
pub fn written(&self) -> usize {
self.written
}
}
impl core::fmt::Debug for Tally<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Tally")
.field("written", &self.written)
.finish_non_exhaustive()
}
}
impl Encode for Tally<'_> {
#[inline]
fn write_byte(&mut self, byte: u8) -> Result<()> {
self.inner.write_byte(byte)?;
self.written = self.written.saturating_add(1);
Ok(())
}
#[inline]
fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
self.inner.write_bytes(bytes)?;
self.written = self.written.saturating_add(bytes.len());
Ok(())
}
#[inline]
fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional);
}
#[inline]
fn write_varint_u64(&mut self, value: u64) -> Result<()> {
self.inner.write_varint_u64(value)?;
self.written = self.written.saturating_add(crate::varint_len(value));
Ok(())
}
}
#[inline]
pub fn read_version<D: Decode + ?Sized>(decoder: &mut D, known: u32) -> Result<u32> {
let raw = decoder.read_varint_u64()?;
if raw == 0 {
return Err(SerialError::InvalidVersion { version: 0 });
}
let version = u32::try_from(raw).map_err(|_| SerialError::IntegerOutOfRange)?;
if version != known && decoder.config().canonical {
return Err(SerialError::NonCanonical {
reason: "versioned struct version",
});
}
Ok(version)
}
#[inline]
pub fn read_body_len<D: Decode + ?Sized>(decoder: &mut D) -> Result<usize> {
let declared = decoder.read_varint_u64()?;
let remaining = decoder.remaining_hint();
let over_input = remaining.is_some_and(|r| declared > r as u64);
if declared > decoder.max_alloc() as u64 || over_input {
return Err(SerialError::InvalidLength {
declared,
remaining: remaining.unwrap_or(0),
});
}
usize::try_from(declared).map_err(|_| SerialError::IntegerOutOfRange)
}
#[inline]
pub fn body_decoder(
bytes: &[u8],
config: Config,
depth: usize,
unbacked: usize,
) -> Decoder<'_> {
Decoder::nested(bytes, config, depth, unbacked)
}
#[inline]
pub fn finish_body(body: &Decoder<'_>, wire_version: u32, known_version: u32) -> Result<usize> {
let _ = (wire_version, known_version);
if !body.is_empty() && body.config().canonical {
return Err(SerialError::NonCanonical {
reason: "versioned body",
});
}
Ok(Decode::unbacked(body))
}
#[inline]
pub fn settle_body<D: Decode + ?Sized>(
decoder: &mut D,
before: usize,
after: usize,
) -> Result<()> {
if after > before {
decoder.charge_unbacked(after - before)?;
}
Ok(())
}
#[inline]
pub fn check_retired<F>(body: &Decoder<'_>, start: usize, write_default: F) -> Result<()>
where
F: FnOnce(&mut Encoder) -> Result<()>,
{
if !body.config().canonical {
return Ok(());
}
let slot = body
.consumed()
.and_then(|consumed| consumed.get(start..))
.unwrap_or_default();
let mut expected = Encoder::with_capacity(slot.len());
write_default(&mut expected)?;
if expected.as_bytes() != slot {
return Err(SerialError::NonCanonical {
reason: "retired field",
});
}
Ok(())
}
#[inline]
pub fn check_body_len(declared: usize, written: usize) -> Result<()> {
if declared != written {
return Err(SerialError::custom(
"pack-io: a field's `encoded_len` disagrees with its `serialize`; the versioned body \
length would be wrong",
));
}
Ok(())
}
#[inline]
pub fn count_with<F>(write: F) -> Result<usize>
where
F: FnOnce(&mut SizeCounter) -> Result<()>,
{
let mut counter = SizeCounter::default();
write(&mut counter)?;
Ok(counter.count())
}
#[inline]
pub fn unknown_variant<T>(kind: &'static str, index: u64) -> Result<T> {
Err(SerialError::UnknownVariant { kind, index })
}
}
#[cfg(all(doctest, feature = "derive", feature = "std"))]
#[doc = include_str!("../docs/MIGRATION.md")]
pub struct MigrationGuideDoctests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn version_matches_cargo_manifest() {
assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}
#[test]
fn tier_one_encode_decode_round_trips_a_tuple() {
use alloc::string::String;
let bytes = encode(&(1_u64, true, String::from("hello"))).expect("encode");
let back: (u64, bool, String) = decode(&bytes).expect("decode");
assert_eq!(back, (1, true, String::from("hello")));
}
}