---
# System prepended metadata

title: Packable

---

# Packable

Genericity over a boolean

- Not integrate it
    - Pros: simpler codebase
    - Cons: inneficient
- Integrate it the way it was (open PR)
    - Pros: more efficient
    - Cons: complex codebase
- 2 versions of a type: checked and unchecked
    - Cons: hardly maintainable




```rust=
pub const VERIFIED: bool = true;
pub const UNVERIFIED: bool = false;

Packable::unpack::<_, VERIFIED>(unpacker)

pub trait Packable: Sized {
    /// The error type that can be returned if some semantic error occurs while unpacking.
    ///
    /// It is recommended to use [`Infallible`](core::convert::Infallible) if this kind of error cannot happen or
    /// [`UnknownTagError`] when implementing this trait for an enum.
    type UnpackError: Debug;

    /// Packs this value into the given [`Packer`].
    fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error>;

    /// The size of the value in bytes after being packed.
    fn packed_len(&self) -> usize;

    /// Unpacks this value from the given [`Unpacker`].
    fn unpack<U: Unpacker, const VERIFY: bool>(
        unpacker: &mut U,
    ) -> Result<Self, UnpackError<Self::UnpackError, U::Error>>;
}

/// Extension trait for types that implement `Packable`.
pub trait PackableExt: Packable {
    /// Convenience method that packs this value into a [`Vec<u8>`].
    fn pack_to_vec(&self) -> Vec<u8>;

    /// Unpacks this value from a type that implements [`AsRef<[u8]>`].
    fn unpack_verified<T: AsRef<[u8]>>(
        bytes: T,
    ) -> Result<Self, UnpackError<<Self as Packable>::UnpackError, UnexpectedEOF>>;
    
        /// Unpacks this value from a type that implements [`AsRef<[u8]>`].
    fn unpack_unverified<T: AsRef<[u8]>>(
        bytes: T,
    ) -> Result<Self, UnpackError<<Self as Packable>::UnpackError, UnexpectedEOF>>;
}
```

