### Attribute Usage with Serde Source: https://docs.rs/bincode/latest/bincode/serde/index Example of using the `#[bincode(with_serde)]` attribute for fields implementing Serde traits. ```APIDOC ## Using `#[bincode(with_serde)]` Attribute For interop with bincode’s `derive` feature, you can use the `#[bincode(with_serde)]` attribute on each field that implements Serde’s traits. ```rust #[derive(Serialize, Deserialize)] pub struct SerdeType { // ... } #[derive(Decode, Encode)] pub struct StructWithSerde { #[bincode(with_serde)] pub serde: SerdeType, } #[derive(Decode, Encode)] pub enum EnumWithSerde { Unit(#[bincode(with_serde)] SerdeType), Struct { #[bincode(with_serde)] serde: SerdeType, }, } ``` ``` -------------------------------- ### Manual Implementation Example Source: https://docs.rs/bincode/latest/bincode/de/trait.Decode Demonstrates how to manually implement the Decode trait for a struct, showing the generated code structure and how to handle decoding of fields. ```APIDOC ## Implementing this trait manually If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Decode)]`, build and check your `target/generated/bincode/` folder. This should generate a `_Decode.rs` file. For this struct: ```rust struct Entity { pub x: f32, pub y: f32, } ``` It will look something like: ```rust impl bincode::Decode for Entity { fn decode>( decoder: &mut D, ) -> core::result::Result { Ok(Self { x: bincode::Decode::decode(decoder)?, y: bincode::Decode::decode(decoder)?, }) } } impl<'de, Context> bincode::BorrowDecode<'de, Context> for Entity { fn borrow_decode>( decoder: &mut D, ) -> core::result::Result { Ok(Self { x: bincode::BorrowDecode::borrow_decode(decoder)?, y: bincode::BorrowDecode::borrow_decode(decoder)?, }) } } ``` From here you can add/remove fields, or add custom logic. To get specific integer types, you can use: ```rust let x: u8 = bincode::Decode::::decode(decoder)?; let x = >::decode(decoder)?; ``` ``` -------------------------------- ### Migrating bincode Options to Configuration (Rust) Source: https://docs.rs/bincode/latest/bincode/migration_guide/index Demonstrates the conversion of bincode 1.x Option configurations to bincode 2.x Configuration settings. This involves changing method names and the overall configuration structure. ```rust bincode_1::DefaultOptions::new().with_varint_encoding() bincode_2::config::legacy().with_variable_int_encoding() ``` -------------------------------- ### Bincode 2 Migration with Serde Feature (Rust) Source: https://docs.rs/bincode/latest/bincode/migration_guide/index Shows how to integrate bincode 2 with the `serde` feature enabled for serialization and deserialization. This requires adding the feature to Cargo.toml and using the `bincode::serde::*` functions. ```rust [dependencies] bincode = { version = "2.0", features = ["serde"] } # Optionally you can disable the `derive` feature: # bincode = { version = "2.0", default-features = false, features = ["std", "serde"] } ``` ```rust Bincode 1| Bincode 2 --- `bincode::deserialize(&[u8])`| `bincode::serde::decode_from_slice(&[u8], Configuration)` | `bincode::serde::borrow_decode_from_slice(&[u8], Configuration)` `bincode::deserialize_from(std::io::Read)`| `bincode::serde::decode_from_std_read(std::io::Read, Configuration)` `bincode::deserialize_from_custom(BincodeRead)`| `bincode::serde::decode_from_reader(Reader, Configuration)` | `bincode::serialize(T)`| `bincode::serde::encode_to_vec(T, Configuration)` `bincode::serde::encode_into_slice(T, &mut [u8], Configuration)` `bincode::serialize_into(std::io::Write, T)`| `bincode::serde::encode_into_std_write(T, std::io::Write, Configuration)` `bincode::serialized_size(T)`| Currently not implemented ``` -------------------------------- ### bincode v2 Encoding Functions Source: https://docs.rs/bincode/latest/bincode/migration_guide/index This snippet demonstrates the new functions for encoding data into a vector or a writer in bincode v2. These replace the v1 `serialize` functions and accept a `Configuration` for advanced usage. ```rust // Equivalent to bincode::serialize(T) bincode::encode_to_vec(value, bincode::config::legacy()); bincode::encode_into_slice(value, &mut buffer, bincode::config::legacy()); // Equivalent to bincode::serialize_into(std::io::Write, T) bincode::encode_into_std_write(value, writer, bincode::config::legacy()); ``` -------------------------------- ### Manual bincode Encode Implementation Example (Rust) Source: https://docs.rs/bincode/latest/bincode/enc/trait.Encode An example demonstrating how to manually implement the `bincode::Encode` trait for a custom struct `Entity`. This involves defining the `encode` method and explicitly calling `bincode::Encode::encode` for each field. This approach is useful for adding custom encoding logic or when the `derive` feature is not used. ```Rust struct Entity { pub x: f32, pub y: f32, } impl bincode::Encode for Entity { fn encode( &self, encoder: &mut E, ) -> core::result::Result<(), bincode::error::EncodeError> { bincode::Encode::encode(&self.x, encoder)?; bincode::Encode::encode(&self.y, encoder)?; Ok(()) } } ``` -------------------------------- ### Integrating External Libraries with bincode Derive Source: https://docs.rs/bincode/latest/bincode/migration_guide/index This code demonstrates how to use bincode's derive macros with external libraries that implement Serde traits but not bincode's Encode/Decode traits. It involves enabling the 'serde' feature and using `#[bincode(with_serde)]` or `bincode::serde::Compat`. ```rust // Assuming MyExternalType implements serde::Serialize and serde::Deserialize // but not bincode::Encode and bincode::Decode #[derive(bincode::Encode, bincode::Decode)] struct MyStruct { #[bincode(with_serde)] external_field: MyExternalType, } // Alternatively, using Compat wrapper #[derive(bincode::Encode, bincode::Decode)] struct AnotherStruct { external_field: bincode::serde::Compat, } #[derive(bincode::Encode, bincode::Decode)] struct BorrowingStruct { external_field: bincode::serde::BorrowCompat<'a, MyExternalType>, } ``` -------------------------------- ### Derive Macros for Serialization and Deserialization Source: https://docs.rs/bincode/latest/bincode/migration_guide/index This snippet shows how to use bincode-derive macros for encoding and decoding, which can be used alongside serde-derive. These macros simplify the process of making types serializable and deserializable by bincode. ```rust #[derive(bincode::Encode)] struct MyStruct; #[derive(bincode::Decode)] struct AnotherStruct; // Can be used side-by-side with serde #[derive(serde::Serialize, bincode::Encode)] struct CombinedStruct; #[derive(serde::Deserialize, bincode::Decode)] struct AnotherCombinedStruct; ``` -------------------------------- ### Rust: ZigZag Integer Encoding Example Source: https://docs.rs/bincode/latest/src/bincode/config.rs Demonstrates the ZigZag encoding for signed integers, which maps signed integers to unsigned integers for efficient storage. It handles positive and negative values, including the minimum and maximum values of i64. ```rust # use bincode::config::{Fixint, Limit, NoLimit, Varint, Configuration}; # use bincode::{config::IntEncoding, config::Endianness}; # trait InternalEndianConfig { const ENDIAN: Endianness; } # trait InternalIntEncodingConfig { const INT_ENCODING: IntEncoding; } # trait InternalLimitConfig { const LIMIT: Option; } # impl InternalEndianConfig for Configuration { # const ENDIAN: Endianness = E::ENDIAN; # } # impl InternalIntEncodingConfig for Configuration { # const INT_ENCODING: IntEncoding = I::INT_ENCODING; # } # impl InternalLimitConfig for Configuration { # const LIMIT: Option = L::LIMIT; # } # impl Configuration { # fn generate() -> Configuration { unimplemented!() } # pub const fn with_variable_int_encoding(self) -> Configuration { unimplemented!() } # pub const fn with_fixed_int_encoding(self) -> Configuration { unimplemented!() } # pub const fn with_limit(self) -> Configuration> { unimplemented!() } # pub const fn with_no_limit(self) -> Configuration { unimplemented!() } # } # fn zigzag(n: i64) -> u64 { # match n { # 0 => 0, # v if v < 0 => !(v as u64) * 2 + 1, # v if v > 0 => (v as u64) * 2, # _ => unreachable!(), # } # } assert_eq!(zigzag(0), 0); assert_eq!(zigzag(-1), 1); assert_eq!(zigzag(1), 2); assert_eq!(zigzag(-2), 3); assert_eq!(zigzag(2), 4); // etc assert_eq!(zigzag(i64::min_value()), u64::max_value()); ``` -------------------------------- ### Serde Integration Example with Bincode Derive Source: https://docs.rs/bincode/latest/src/bincode/features/serde/mod.rs Demonstrates how to use bincode's `#[bincode(with_serde)]` attribute to integrate serde-compatible types within bincode's derive macros. This allows seamless serialization and deserialization of structs and enums containing fields that implement serde's traits. ```rust # #[cfg(feature = "derive")] # mod foo { # use bincode::{Decode, Encode}; # use serde_derive::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct SerdeType { // ... } #[derive(Decode, Encode)] pub struct StructWithSerde { #[bincode(with_serde)] pub serde: SerdeType, } #[derive(Decode, Encode)] pub enum EnumWithSerde { Unit(#[bincode(with_serde)] SerdeType), Struct { #[bincode(with_serde)] serde: SerdeType, }, } # } ``` -------------------------------- ### bincode v2 Decoding Functions Source: https://docs.rs/bincode/latest/bincode/migration_guide/index This section illustrates the updated functions for decoding byte slices and readers in bincode v2. It replaces the v1 `deserialize` functions with more explicit names and introduces a `Configuration` parameter for finer control. ```rust // Equivalent to bincode::deserialize(&[u8]) bincode::decode_from_slice(&bytes, bincode::config::legacy()); bincode::borrow_decode_from_slice(&bytes, bincode::config::legacy()); // Equivalent to bincode::deserialize_from(std::io::Read) bincode::decode_from_std_read(reader, bincode::config::legacy()); bincode::decode_from_reader(reader, bincode::config::legacy()); ``` -------------------------------- ### Tuple Serialization Example with Bincode Source: https://docs.rs/bincode/latest/bincode/spec/index Demonstrates the serialization of a tuple containing different integer types. Bincode encodes tuple elements sequentially without additional overhead, based on their respective types and the configured endianness. ```Rust let tuple = (u32::min_value(), i32::max_value()); // (0, 2147483647) let encoded = bincode::encode_to_vec(tuple, bincode::config::legacy()).unwrap(); // Using legacy config for example // Expected byte representation for (0u32, 2147483647i32) in little-endian // u32::min_value() is 0 (4 bytes) i32::max_value() is 2147483647 (0x7FFFFFFF) (4 bytes) let expected_bytes = vec![0, 0, 0, 0, 255, 255, 255, 127]; assert_eq!(encoded.as_slice(), expected_bytes.as_slice()); println!("Encoded tuple: {:?}", encoded); ``` -------------------------------- ### Enabling Bincode Derive Feature (Rust) Source: https://docs.rs/bincode/latest/bincode/migration_guide/index Illustrates how to enable the `bincode-derive` feature in `Cargo.toml`, which is used for generating serialization and deserialization code. This is enabled by default but can be explicitly managed. ```rust [dependencies] bincode = "2.0" # If you need `no_std` with `alloc`: # bincode = { version = "2.0", default-features = false, features = ["derive", "alloc"] } # If you need `no_std` and no `alloc`: ``` -------------------------------- ### EncoderImpl Usage Example - Rust Source: https://docs.rs/bincode/latest/src/bincode/enc/encoder.rs Demonstrates how to use the `EncoderImpl` struct with a `SliceWriter` and a specific configuration (`legacy().with_big_endian()`). This example shows encoding a `u32` value and verifying the bytes written and the final state of the slice. ```Rust let slice: &mut [u8] = &mut [0, 0, 0, 0]; let config = bincode::config::legacy().with_big_endian(); let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config); // this u32 can be any Encodable 5u32.encode(&mut encoder).unwrap(); assert_eq!(encoder.into_writer().bytes_written(), 4); assert_eq!(slice, [0, 0, 0, 5]); ``` -------------------------------- ### Decoding Bytes in Arena Context with Rust Source: https://docs.rs/bincode/latest/src/bincode/de/mod.rs This Rust example demonstrates decoding a `BytesInArena` type which requires a specific context, `&'a bumpalo::Bump`. The `Decode` implementation for `BytesInArena` is shown, highlighting how to utilize the provided context during the decoding process. The `todo!()` macro indicates that the actual decoding logic needs to be implemented. ```Rust use bincode::de::Decoder; use bincode::error::DecodeError; struct BytesInArena<'a>(bumpalo::collections::Vec<'a, u8>); impl<'a> bincode::Decode<&'a bumpalo::Bump> for BytesInArena<'a> { fn decode(decoder: &mut D) -> Result { todo!() } # } ``` -------------------------------- ### Implement bincode::Encode Trait Source: https://docs.rs/bincode/latest/src/bincode/enc/mod.rs Demonstrates how to manually implement the `bincode::Encode` trait for a struct. This is useful for custom serialization logic. The example shows encoding fields sequentially and returning a success or error result. ```Rust impl bincode::Encode for Entity { fn encode( &self, encoder: &mut E, ) -> core::result::Result<(), bincode::error::EncodeError> { bincode::Encode::encode(&self.x, encoder)?; bincode::Encode::encode(&self.y, encoder)?; Ok(()) } } ``` -------------------------------- ### Create Standard bincode Configuration Source: https://docs.rs/bincode/latest/bincode/config/index Demonstrates how to create a standard bincode configuration using the `config::standard()` method. Users can then customize endianness (big or little) and integer encoding (variable or fixed). Ensure the same configuration is used for both encoding and decoding. ```rust let config = bincode::config::standard() // pick one of: .with_big_endian() .with_little_endian() // pick one of: .with_variable_int_encoding() .with_fixed_int_encoding(); ``` -------------------------------- ### Rust: Create a new DecoderImpl instance Source: https://docs.rs/bincode/latest/bincode/de/struct.DecoderImpl Shows how to construct a new DecoderImpl instance. This function takes a reader, a configuration object, and a context as arguments. ```Rust pub fn new(reader: R, config: C, context: Context) -> DecoderImpl ``` -------------------------------- ### Create Legacy bincode Configuration Source: https://docs.rs/bincode/latest/bincode/config/index Shows how to create the legacy default configuration for bincode, which was the default in version 1.0. This function provides a pre-defined configuration that can be used directly. ```rust let config = bincode::config::legacy(); ``` -------------------------------- ### Rust: bincode Any Trait Implementation Source: https://docs.rs/bincode/latest/bincode/config/struct.Configuration Implements the `Any` trait for any type `T`, providing a way to get the `TypeId` of a value. This is a blanket implementation applicable to all types. ```rust impl Any for T where T: 'static + ?Sized, ``` ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Decode RangeInclusive in Rust Source: https://docs.rs/bincode/latest/src/bincode/de/impls.rs Implements the `Decode` trait for `RangeInclusive`. It decodes the start and end values of the inclusive range. The type `T` must also implement `Decode`. ```rust impl Decode for RangeInclusive where T: Decode, { fn decode>(decoder: &mut D) -> Result { let min = T::decode(decoder)?; let max = T::decode(decoder)?; Ok(RangeInclusive::new(min, max)) } } ``` -------------------------------- ### Compat Struct Documentation Source: https://docs.rs/bincode/latest/bincode/serde/struct.Compat Details on the Compat wrapper struct, its purpose, and its trait implementations. ```APIDOC ## Struct Compat ### Description Wrapper struct that implements `Decode` and `Encode` on any type that implements serde’s `DeserializeOwned` and `Serialize` respectively. This works for most types, but if you’re dealing with borrowed data consider using `BorrowCompat` instead. Available on **crate feature `serde`** only. ### Fields - **0**: T - The wrapped value. ### Trait Implementations - **`BorrowDecode<'de, Context>` for `Compat`**: Implements `borrow_decode` for decoding with a `BorrowDecoder`. - **`Clone` for `Compat`**: Implements `clone` and `clone_from`. - **`Debug` for `Compat`**: Implements `fmt` for debugging. - **`Decode` for `Compat`**: Implements `decode` for bincode decoding. - **`Default` for `Compat`**: Implements `default`. - **`Display` for `Compat`**: Implements `fmt` for display. - **`Encode` for `Compat`**: Implements `encode` for bincode encoding. - **`Hash` for `Compat`**: Implements `hash` and `hash_slice`. - **`Ord` for `Compat`**: Implements `cmp`, `max`, `min`, and `clamp`. - **`PartialOrd` for `Compat`**: Implements `partial_cmp`, `lt`, `le`, `gt`, and `ge`. - **`Eq` for `Compat`** - **`StructuralPartialEq` for `Compat`** ### Auto Trait Implementations - **`Freeze` for `Compat`** - **`RefUnwindSafe` for `Compat`** - **`Send` for `Compat`** - **`Sync` for `Compat`** - **`Unpin` for `Compat`** - **`UnwindSafe` for `Compat`** ``` -------------------------------- ### Encode Implementation for Range in Rust Source: https://docs.rs/bincode/latest/src/bincode/enc/impls.rs This implementation encodes a `Range` by encoding its `start` and `end` bounds individually. It requires that the type `T` implements the `Encode` trait. ```rust impl Encode for Range where T: Encode, { fn encode(&self, encoder: &mut E) -> Result<(), EncodeError> { self.start.encode(encoder)?; self.end.encode(encoder)?; Ok(()) } } ``` -------------------------------- ### Bincode Writer Module Documentation Source: https://docs.rs/bincode/latest/bincode/enc/write/index Overview of the structs and traits available in the bincode::enc::write module for data encoding. ```APIDOC ## Module: write ### Description This module contains writer-based structs and traits. Because `std::io::Write` is only limited to `std` and not `core`, we provide our own Writer. ### Structs #### SizeWriter A writer that counts how many bytes were written. This is useful for e.g. pre-allocating buffers bfeore writing to them. #### SliceWriter A helper struct that implements `Writer` for a `&[u8]` slice. ### Traits #### Writer Trait that indicates that a struct can be used as a destination to encode data too. This is used by Encode ``` -------------------------------- ### Encode Implementation for RangeInclusive in Rust Source: https://docs.rs/bincode/latest/src/bincode/enc/impls.rs This implementation encodes an inclusive range `RangeInclusive` by encoding its `start` and `end` bounds individually. It requires that the type `T` implements the `Encode` trait. ```rust impl Encode for RangeInclusive where T: Encode, { fn encode(&self, encoder: &mut E) -> Result<(), EncodeError> { self.start().encode(encoder)?; self.end().encode(encoder)?; Ok(()) } } ``` -------------------------------- ### Get Mutable Slice from Uninitialized Array (Rust) Source: https://docs.rs/bincode/latest/src/bincode/de/impl_core.rs Provides a mutable reference to the initialized portion of an array of `MaybeUninit`. This is an unsafe operation that requires the caller to guarantee that all elements in the specified slice are indeed initialized. ```Rust /// Assuming all the elements are initialized, get a mutable slice to them. /// /// # Safety /// /// It is up to the caller to guarantee that the `MaybeUninit` elements /// really are in an initialized state. /// Calling this when the content is not yet fully initialized causes undefined behavior. /// /// See [`assume_init_mut`] for more details and examples. /// /// [`assume_init_mut`]: MaybeUninit::assume_init_mut // #[unstable(feature = "maybe_uninit_slice", issue = "63569")] // #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")] #[inline(always)] pub unsafe fn slice_assume_init_mut(slice: &mut [MaybeUninit]) -> &mut [T] { // SAFETY: similar to safety notes for `slice_get_ref`, but we have a // mutable reference which is also guaranteed to be valid for writes. unsafe { &mut *(slice as *mut [MaybeUninit] as *mut [T]) } } ``` -------------------------------- ### Encode Implementation for Cell in Rust Source: https://docs.rs/bincode/latest/src/bincode/enc/impls.rs This implementation encodes the value contained within a `Cell`. It requires that the type `T` implements both `Encode` and `Copy`. The `get()` method is used to retrieve the value, which is then encoded. ```rust impl Encode for Cell where T: Encode + Copy, { fn encode(&self, encoder: &mut E) -> Result<(), EncodeError> { T::encode(&self.get(), encoder) } } ``` -------------------------------- ### SliceWriter API Source: https://docs.rs/bincode/latest/bincode/enc/write/struct.SliceWriter Documentation for the bincode::enc::write::SliceWriter struct, including its constructor and methods. ```APIDOC ## Struct SliceWriter ### Description A helper struct that implements `Writer` for a `&[u8]` slice. ### Methods #### `new(bytes: &'storage mut [u8]) -> SliceWriter<'storage>` Create a new instance of `SliceWriter` with the given byte array. #### `bytes_written(&self) -> usize` Return the amount of bytes written so far. ### Trait Implementations #### `impl Writer for SliceWriter<'_>` ##### `write(&mut self, bytes: &[u8]) -> Result<(), EncodeError>` Write `bytes` to the underlying writer. Exactly `bytes.len()` bytes must be written, or else an error should be returned. ### Request Example ```rust use bincode::enc::write::{Writer, SliceWriter}; let destination = &mut [0u8; 100]; let mut writer = SliceWriter::new(destination); writer.write(&[1, 2, 3, 4, 5]).unwrap(); assert_eq!(writer.bytes_written(), 5); assert_eq!(destination[0..6], [1, 2, 3, 4, 5, 0]); ``` ### Response #### Success Response (200) This struct does not have direct HTTP endpoints, so success responses are based on method return types. - `usize`: The number of bytes written (for `bytes_written`). - `Result<(), EncodeError>`: Indicates success or failure of the write operation (for `write`). #### Response Example (See Request Example for usage and return value interpretation) ``` -------------------------------- ### Implement Display for BorrowCompat in Rust Source: https://docs.rs/bincode/latest/src/bincode/features/serde/mod.rs Implements the `Display` trait for the `BorrowCompat` struct. This enables instances of `BorrowCompat` to be formatted using the `{}` specifier, suitable for user-facing output. The implementation forwards the formatting to the wrapped type `T`, provided `T` also implements `Display`. ```rust impl where T: core::fmt::Display, { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } ``` -------------------------------- ### Rust: DecoderImpl methods for accessing reader, config, and context Source: https://docs.rs/bincode/latest/bincode/de/struct.DecoderImpl Provides implementations for accessing the internal reader, configuration, and context of a DecoderImpl instance. These methods are part of the Decoder trait implementation. ```Rust fn reader(&mut self) -> &mut Self::R fn config(&self) -> &Self::C fn context(&mut self) -> &mut Self::Context ``` -------------------------------- ### Implement Display for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the Display trait for BorrowCompat, requiring T to implement Display. This enables formatted string representation of BorrowCompat instances. ```rust impl Display for BorrowCompat { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // ... implementation details ... } } ``` -------------------------------- ### Rust: bincode Configuration Clone Implementation Source: https://docs.rs/bincode/latest/bincode/config/struct.Configuration Provides the `Clone` trait implementation for the `Configuration` struct, allowing configurations to be duplicated. It includes methods for both cloning and copy-assignment. ```rust fn clone(&self) -> Configuration ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Rust: Decoding Primitive Types with Bincode Source: https://docs.rs/bincode/latest/bincode/de/trait.Decode Provides examples of how primitive types like `bool`, `char`, `f32`, `f64`, and various integer types (`i8` through `i128`) can be decoded using the `bincode::Decode` trait. These implementations are often available by default or with specific feature flags. ```rust // Example for decoding bool: let decoded_bool: bool = bincode::Decode::decode(decoder)?; // Example for decoding f32: let decoded_f32: f32 = bincode::Decode::decode(decoder)?; // Example for decoding i64: let decoded_i64: i64 = bincode::Decode::decode(decoder)?; ``` -------------------------------- ### Initialize DecoderImpl in Rust Source: https://docs.rs/bincode/latest/src/bincode/de/decoder.rs This Rust code defines a constructor for the `DecoderImpl` struct. It takes a reader, configuration, and context as input and initializes a new `DecoderImpl` instance. This function is the primary way to create a decoder for processing byte streams. ```Rust impl DecoderImpl { /// Construct a new Decoder pub fn new(reader: R, config: C, context: Context) -> DecoderImpl { DecoderImpl { reader, config, bytes_read: 0, context, } } } ``` -------------------------------- ### Rust: Decoding with Context for Arena Allocation Source: https://docs.rs/bincode/latest/bincode/de/trait.Decode Shows an example of implementing `Decode` for a type that requires a context, specifically `BytesInArena` which uses `bumpalo::collections::Vec` and requires a `bumpalo::Bump` as its context. This highlights how context can be used for managing memory or providing necessary data during decoding. ```rust use bincode::de::Decoder; use bincode::error::DecodeError; struct BytesInArena<'a>(bumpalo::collections::Vec<'a, u8>); impl<'a> bincode::Decode<&'a bumpalo::Bump> for BytesInArena<'a> { fn decode(decoder: &mut D) -> Result { todo!() // Placeholder for actual decoding logic } } ``` -------------------------------- ### OwnedSerdeDecoder Source: https://docs.rs/bincode/latest/bincode/serde/struct.OwnedSerdeDecoder Details about the OwnedSerdeDecoder struct, its purpose, and how to create instances. ```APIDOC ## Struct OwnedSerdeDecoder ### Description Serde decoder encapsulating an owned reader. Available on **crate feature`serde`** only. ### Implementations #### impl OwnedSerdeDecoder ##### pub fn as_deserializer<'a>( &'a mut self, ) -> impl for<'de> Deserializer<'de, Error = DecodeError> + 'a Return a type implementing `serde::Deserializer`. #### impl<'r, C: Config, R: Read> OwnedSerdeDecoder, C, ()>> ##### pub fn from_std_read( src: &'r mut R, config: C, ) -> OwnedSerdeDecoder, C, ()>> where C: Config, Creates the decoder from an `std::io::Read` implementor. #### impl OwnedSerdeDecoder> ##### pub fn from_reader( reader: R, config: C, ) -> OwnedSerdeDecoder> where C: Config, Creates the decoder from a `Reader` implementor. ### Auto Trait Implementations - **impl Freeze for OwnedSerdeDecoder** where DE: Freeze - **impl RefUnwindSafe for OwnedSerdeDecoder** where DE: RefUnwindSafe - **impl Send for OwnedSerdeDecoder** where DE: Send - **impl Sync for OwnedSerdeDecoder** where DE: Sync - **impl Unpin for OwnedSerdeDecoder** where DE: Unpin - **impl UnwindSafe for OwnedSerdeDecoder** where DE: UnwindSafe ``` -------------------------------- ### Rust: DecoderImpl method for context wrapping Source: https://docs.rs/bincode/latest/bincode/de/struct.DecoderImpl Demonstrates the `with_context` method on DecoderImpl, which allows wrapping the decoder with a new context for specific operations. This returns a `WithContext` wrapper. ```Rust fn with_context(&mut self, context: C_new) -> WithContext<'_, Self, C_new> ``` -------------------------------- ### Implement Encode for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the Encode trait for BorrowCompat, where T must implement serde's Serialize trait. This allows encoding a BorrowCompat instance using an Encoder. ```rust impl Encode for BorrowCompat { fn encode(&self, encoder: &mut E) -> Result<(), EncodeError> { // ... implementation details ... } } ``` -------------------------------- ### Rust: Clone to Uninitialized Memory (clone_to_uninit) Source: https://docs.rs/bincode/latest/bincode/serde/struct.Compat This Rust code snippet demonstrates the `clone_to_uninit` function. It's a nightly-only experimental API used for copy-assignment from the source to the destination. It's useful for scenarios where you need to copy data into uninitialized memory. ```rust #### unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Derive Macros Source: https://docs.rs/bincode/latest/bincode/index Documentation for bincode's derive macros used for automatically implementing decoding, encoding, and borrowing decode traits. ```APIDOC ## BorrowDecode`derive` ### Description Derive macro for implementing the `BorrowDecode` trait. ### Method N/A (Attribute Macro) ### Endpoint N/A ### Parameters (Applied as an attribute to a struct or enum) ### Request Example ```rust #[derive(BincodeBorrowDecode)] struct MyStruct { field: u32 } ``` ### Response (N/A) ## Decode`derive` ### Description Derive macro for implementing the `Decode` trait. ### Method N/A (Attribute Macro) ### Endpoint N/A ### Parameters (Applied as an attribute to a struct or enum) ### Request Example ```rust #[derive(BincodeDecode)] struct MyStruct { field: u32 } ``` ### Response (N/A) ## Encode`derive` ### Description Derive macro for implementing the `Encode` trait. ### Method N/A (Attribute Macro) ### Endpoint N/A ### Parameters (Applied as an attribute to a struct or enum) ### Request Example ```rust #[derive(BincodeEncode)] struct MyStruct { field: u32 } ``` ### Response (N/A) ``` -------------------------------- ### Serde Wrapper Structs Source: https://docs.rs/bincode/latest/bincode/serde/index Wrapper structs that provide interopability between bincode's Decode/Encode traits and Serde's Deserialize/Serialize traits. ```APIDOC ## Wrapper Structs for Serde Interop ### Compat Wrapper struct that implements `Decode` and `Encode` on any type that implements `serde`’s `DeserializeOwned` and `Serialize` respectively. ### BorrowCompat Wrapper struct that implements `BorrowDecode` and `Encode` on any type that implements `serde`’s `Deserialize` and `Serialize` respectively. This is mostly used on `&[u8]` and `&str`, for other types consider using `Compat` instead. ``` -------------------------------- ### Implement BorrowDecode for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the BorrowDecode trait for BorrowCompat, where T must implement serde's Deserialize trait. This allows decoding a BorrowCompat instance using a BorrowDecoder. ```rust impl<'de, T, Context> BorrowDecode<'de, Context> for BorrowCompat where T: Deserialize<'de> { fn borrow_decode>(decoder: &mut D) -> Result { // ... implementation details ... } } ``` -------------------------------- ### Implement Clone for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the Clone trait for BorrowCompat, requiring T to also implement Clone. This allows creating a copy of a BorrowCompat instance. ```rust impl Clone for BorrowCompat { fn clone(&self) -> BorrowCompat { // ... implementation details ... } fn clone_from(&mut self, source: &Self) { // ... implementation details ... } } ``` -------------------------------- ### Rust: Bincode Standard Configuration Source: https://docs.rs/bincode/latest/src/bincode/config.rs Demonstrates how to create the standard bincode configuration, which defaults to little-endian and variable integer encoding. This configuration is suitable for most use cases. ```rust /// The default config for bincode 2.0. By default this will be: /// - Little endian /// - Variable int encoding pub const fn standard() -> Configuration { generate() } ``` -------------------------------- ### Clone Data to Uninitialized Memory (Rust) Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat The `clone_to_uninit` function is an experimental API for cloning data from self to a destination in memory. It copies the contents of `self` to the provided mutable raw pointer `dest`. This function requires nightly Rust and is marked as unsafe, indicating potential memory safety concerns. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Rust: bincode Configuration Default Implementation Source: https://docs.rs/bincode/latest/bincode/config/struct.Configuration Provides the `Default` trait implementation for the `Configuration` struct, allowing the creation of a default configuration using `Configuration::default()`. ```rust fn default() -> Self ``` -------------------------------- ### Implement Debug for BorrowCompat in Rust Source: https://docs.rs/bincode/latest/src/bincode/features/serde/mod.rs Implements the `Debug` trait for the `BorrowCompat` struct. This allows instances of `BorrowCompat` to be formatted using the `{:?}` specifier, typically used for developer-facing output. It requires the wrapped type `T` to also implement `Debug`. ```rust impl where T: core::fmt::Debug, { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("BorrowCompat").field(&self.0).finish() } } ``` -------------------------------- ### Rust: TryInto Trait Implementation Source: https://docs.rs/bincode/latest/bincode/serde/struct.Compat This Rust snippet showcases the `TryInto` trait implementation, providing a fallible conversion mechanism. It calls `TryFrom`, returning a `Result` to signal success or failure. It's similar to `Into` but accounts for potential conversion errors. ```rust ### impl TryInto for T where U: TryFrom, #### type Error = >::Error #### fn try_into(self) -> Result>::Error> ``` -------------------------------- ### BorrowDecode with Serde Compatibility Source: https://docs.rs/bincode/latest/bincode/de/trait.BorrowDecode Provides `BorrowDecode` implementations for types that are compatible with Serde deserialization. `BorrowCompat` requires `T: Deserialize<'de>`, and `Compat` requires `T: DeserializeOwned`. Both require the `serde` crate feature. ```APIDOC ## POST /websites/rs_bincode/borrow_decode ### Description Decodes types compatible with Serde deserialization by borrowing from the provided decoder. Requires the `serde` crate feature. ### Method POST ### Endpoint /websites/rs_bincode/borrow_decode ### Parameters #### Request Body - **decoder** (BorrowDecoder) - Required - The decoder to borrow from. ### Request Example ```json { "decoder": "" } ``` ### Response #### Success Response (200) - **Self** (BorrowCompat | Compat) - The decoded Serde-compatible type. - **DecodeError** - If decoding fails. #### Response Example ```json { "result": "" } ``` ``` -------------------------------- ### Rust: Bincode Legacy Configuration Source: https://docs.rs/bincode/latest/src/bincode/config.rs Shows how to generate the legacy bincode configuration, mimicking the default behavior of bincode 1.0. This configuration uses little-endian and fixed integer encoding. ```rust /// Creates the "legacy" default config. This is the default config that was present in bincode 1.0 /// - Little endian /// - Fixed int length encoding pub const fn legacy() -> Configuration { generate() } ``` -------------------------------- ### Serde Integration Functions Source: https://docs.rs/bincode/latest/bincode/serde/index Functions for encoding and decoding types that implement Serde traits using bincode. ```APIDOC ## Functions for Serde Integration ### borrow_decode_from_slice Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read. ### decode_from_slice Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read. ### encode_into_slice Encode the given value into the given slice. Returns the amount of bytes that have been written. ### encode_to_vec Encode the given value into a `Vec` with the given `Config`. See the config module for more information. ### seed_decode_from_slice Decode a borrowed type from the given slice using a seed. Some parts of the decoded type are expected to be referring to the given slice. ``` -------------------------------- ### Rust: Bincode Variable Integer Encoding Source: https://docs.rs/bincode/latest/src/bincode/config.rs Explains and demonstrates bincode's variable integer encoding strategy. This method efficiently encodes smaller integers using fewer bytes, with specific byte prefixes (251-254) indicating the size of the subsequent integer data. ```rust /// Makes bincode encode all integer types with a variable integer encoding. /// /// Encoding an unsigned integer v (of any type excepting u8) works as follows: /// /// 1. If `u < 251`, encode it as a single byte with that value. /// 2. If `251 <= u < 2**16`, encode it as a literal byte 251, followed by a u16 with value `u`. /// 3. If `2**16 <= u < 2**32`, encode it as a literal byte 252, followed by a u32 with value `u`. /// 4. If `2**32 <= u < 2**64`, encode it as a literal byte 253, followed by a u64 with value `u`. /// 5. If `2**64 <= u < 2**128`, encode it as a literal byte 254, followed by a u128 with value `u`. /// /// Then, for signed integers, we first convert to unsigned using the zigzag algorithm, /// and then encode them as we do for unsigned integers generally. The reason we use this /// algorithm is that it encodes those values which are close to zero in less bytes; the /// obvious algorithm, where we encode the cast values, gives a very large encoding for all /// negative values. /// /// The zigzag algorithm is defined as follows: /// /// ```rust /// # type Signed = i32; /// # type Unsigned = u32; /// fn zigzag(v: Signed) -> Unsigned { /// match v { /// 0 => 0, /// // To avoid the edge case of Signed::min_value() /// // !n is equal to `-n - 1`, so this is: /// // !n * 2 + 1 = 2(-n - 1) + 1 = -2n - 2 + 1 = -2n - 1 ``` -------------------------------- ### Derive Macros for Serde Integration in Rust Source: https://docs.rs/bincode/latest/bincode/serde/index Demonstrates how to use bincode's derive macros with serde traits for custom struct and enum serialization. Requires the 'serde' and 'derive' features to be enabled. This method allows for specific fields to be handled via serde while others use bincode's native derive. ```rust #[derive(Serialize, Deserialize)] pub struct SerdeType { // ... } #[derive(Decode, Encode)] pub struct StructWithSerde { #[bincode(with_serde)] pub serde: SerdeType, } #[derive(Decode, Encode)] pub enum EnumWithSerde { Unit(#[bincode(with_serde)] SerdeType), Struct { #[bincode(with_serde)] serde: SerdeType, }, } ``` -------------------------------- ### Implement Default for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the Default trait for BorrowCompat, requiring T to implement Default. This allows creating a default instance of BorrowCompat. ```rust impl Default for BorrowCompat { fn default() -> BorrowCompat { // ... implementation details ... } } ``` -------------------------------- ### Implement PartialEq for BorrowCompat Source: https://docs.rs/bincode/latest/bincode/serde/struct.BorrowCompat Implements the PartialEq trait for BorrowCompat, requiring T to implement PartialEq. This enables equality comparisons for BorrowCompat instances. ```rust impl PartialEq for BorrowCompat { fn eq(&self, other: &BorrowCompat) -> bool { // ... implementation details ... } fn ne(&self, other: &Rhs) -> bool { // ... implementation details ... } } ``` -------------------------------- ### Encode to Slice and Writer Source: https://docs.rs/bincode/latest/bincode/index Functions for encoding Rust values into byte slices, vectors, and standard I/O writers. ```APIDOC ## encode_into_slice ### Description Encode the given value into the given slice. Returns the amount of bytes that have been written. ### Method (Not specified, typically POST or PUT for encoding operations) ### Endpoint (Not applicable for library functions) ### Parameters * **value** (T) - The value to encode. * **slice** (&mut [u8]) - The mutable byte slice to encode into. ### Request Example (Not applicable for library functions) ### Response #### Success Response * **bytes_written** (usize) - The number of bytes written to the slice. #### Response Example ```json { "bytes_written": 15 } ``` ## encode_into_writer ### Description Encode the given value into a custom Writer. ### Method (Not specified, typically POST or PUT for encoding operations) ### Endpoint (Not applicable for library functions) ### Parameters * **value** (T) - The value to encode. * **writer** (impl Writer) - The custom writer to encode into. ### Request Example (Not applicable for library functions) ### Response #### Success Response (Typically returns () or bytes written on success, details not specified) #### Response Example (Not specified) ## encode_into_std_write ### Description Encode the given value into any type that implements `std::io::Write`, e.g. `std::fs::File`, with the given `Config`. See the config module for more information. Returns the amount of bytes written. ### Method (Not specified, typically POST or PUT for encoding operations) ### Endpoint (Not applicable for library functions) ### Parameters * **value** (T) - The value to encode. * **writer** (impl std::io::Write) - The writer to encode into. * **config** (Config) - The bincode configuration. ### Request Example (Not applicable for library functions) ### Response #### Success Response * **bytes_written** (usize) - The number of bytes written to the writer. #### Response Example ```json { "bytes_written": 20 } ``` ## encode_to_vec ### Description Encode the given value into a `Vec` with the given `Config`. See the config module for more information. ### Method (Not specified, typically POST or PUT for encoding operations) ### Endpoint (Not applicable for library functions) ### Parameters * **value** (T) - The value to encode. * **config** (Config) - The bincode configuration. ### Request Example (Not applicable for library functions) ### Response #### Success Response * **encoded_vec** (Vec) - The resulting vector of bytes. #### Response Example ```json { "encoded_vec": [1, 2, 3, 4, 5] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.