Skip to main content

Value

Enum Value 

Source
pub enum Value<'a> {
    Int(Int),
    Str(Str<'a>),
    List(List<'a>),
    Dict(Dict<'a>),
}
Expand description

A Bencode value is either an Int, a Str, a List or a Dict

Note that Value carries a lifetime parameter for borrowed data. This is useful for two reasons:

  1. When encoding data, you can avoid unnecessary allocations by just referencing existing data. Usually, the object is serialized right away and the object is dropped afterwards.
  2. When decoding data, all byte strings and dictionary keys are borrowed from the input buffer. This avoids unnecessary allocations and is key to performance. Especially since keys are often quite short, a separate Vec allocation per key would be very wasteful. The idea here is also that after decoding, the object is used and dispatched right away and then dropped. Actually required and useful data can be cloned out of the object if needed.

Values are meant to be constructed using a combination of the provided macros int!, str!, list! and dict!:

use bencode_minimal::*;

let alice = "Alice".to_string();

let v = dict! {
    "age" => int!(42),
    "name" => str!("John"),                     // <-- static
    "friends" => list![
        str!(alice.as_str()),                   // <-- borrowed
        dict! {
            "name" => str!("Bob".to_string()),  // <-- owned
            "data" => str!(vec![48u8, 49, 50]), // <-- owned
        }
    ]
};

let bin = v.encode();
assert_eq!(&bin, b"d3:agei42e7:friendsl5:Aliced4:data3:0124:name3:Bobee4:name4:Johne");

Variants§

§

Int(Int)

§

Str(Str<'a>)

§

List(List<'a>)

§

Dict(Dict<'a>)

Implementations§

Source§

impl<'a> Value<'a>

Source

pub fn get<'b, T: TryFromValue<'b>>(&'b self, key: &'static str) -> Option<T>

Assume the value is a dictionary and get the value for the given key, converted into the desired type using TryFromValue

Fails if the value is not a dictionary, the key does not exist or the value cannot be converted into the desired type.

use bencode_minimal::*;

let v = dict! {
    "t" => str!(b"1234"),
    "y" => str!(b"q"),
    "q" => str!(b"ping"),
    "a" => dict! {
        "id" => str!(vec![5u8; 20]),
    },
};

let ping_query = || {
   let _ = v.get::<&str>("y").filter(|x| *x == "q")?;
   let _ = v.get::<&str>("q").filter(|x| *x == "ping")?;
   let a = v.get::<&Value>("a")?;
   let t = v.get::<&[u8]>("t")?;
   let id = a.get::<[u8;20]>("id")?;
   Some((t, id))
};

let (t, id) = ping_query().unwrap();
assert_eq!(t, b"1234");
assert_eq!(id, [5u8; 20]);
Source

pub fn try_into<'b, T: TryFromValue<'b>>(&'b self) -> Option<T>

Try to convert the Value into the desired type using TryFromValue

Fails if the value cannot be converted into the desired type.

Source

pub fn encode(&self) -> Vec<u8>

Quick encoding into a Vec<u8>

The returned vector is freshly allocated and has a capacity of 1500 bytes to avoid multiple reallocations for typical use cases. Its length is adjusted to the actual encoded size.

Source

pub fn encode_into(&self, buf: &mut Vec<u8>)

Encode into the provided buffer

The provided buffer is cleared before encoding and has the length of the encoded data afterwards. Its capacity is increased as needed but never decreased. Make sure to reuse the buffer when possible to avoid unnecessary allocations.Also, make sure to provide a buffer with sufficient initial capacity to avoid multiple reallocations. When passing the same buffer multiple times, its capacity will grow to the maximum size needed.

Source

pub fn decode(buf: &'a [u8], max_allocs: usize) -> Option<Self>

Try to decode a Value from the provided buffer

The max_allocs parameter limits the number of allocations that may be performed during decoding. This is useful to avoid denial-of-service attacks by providing maliciously crafted input that would cause excessive memory allocations. Each list item and dictionary entry counts as one allocation. If the limit is exceeded, decoding fails and None is returned.

The returned Value borrows all byte strings from the input buffer. The value can therefor not outlive the input buffer. Either deconstruct the value right away (recommended) or use Self::into_owned.

Source

pub fn into_owned(self) -> Value<'static>

Convert the value into an owned version

All borrowed byte strings are cloned into owned Vec<u8>s. Byte strings that are already owned are moved into the new value without cloning. All Vecs and BTreeMaps get unfortunately recreated since there is no way to recycle them.

Trait Implementations§

Source§

impl<'a> Clone for Value<'a>

Source§

fn clone(&self) -> Value<'a>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> Eq for Value<'a>

Source§

impl<'a> Hash for Value<'a>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> Ord for Value<'a>

Source§

fn cmp(&self, other: &Value<'a>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'a> PartialEq for Value<'a>

Source§

fn eq(&self, other: &Value<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> PartialOrd for Value<'a>

Source§

fn partial_cmp(&self, other: &Value<'a>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a> StructuralPartialEq for Value<'a>

Source§

impl<'a> TryFromValue<'a> for &'a Value<'a>

Source§

fn try_from(value: &'a Value<'_>) -> Option<Self>

Auto Trait Implementations§

§

impl<'a> Freeze for Value<'a>

§

impl<'a> RefUnwindSafe for Value<'a>

§

impl<'a> Send for Value<'a>

§

impl<'a> Sync for Value<'a>

§

impl<'a> Unpin for Value<'a>

§

impl<'a> UnsafeUnpin for Value<'a>

§

impl<'a> UnwindSafe for Value<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.