Struct blather::types::params::Params

source ·
pub struct Params { /* private fields */ }
Expand description

Key/value parameters storage with helper methods to make adding and getting common value types slightly more ergonomic and using a plain HashMap.

Uses Strings for both keys and values internally.

Implementations§

source§

impl Params

source

pub fn new() -> Self

Create a new empty parameters object.

source

pub fn clear(&mut self)

Reset all the key/values in Params object.

source

pub fn len(&self) -> usize

Return the number of key/value pairs in the parameter buffer.

source

pub fn is_empty(&self) -> bool

Returns true if the Params collection does not contain any key/value pairs.

source

pub fn get_inner(&self) -> &HashMap<String, String>

Return reference to inner HashMap.

source

pub fn add_param<T: ToString, U: ToString>( &mut self, key: T, value: U ) -> Result<(), Error>

Add a parameter to the parameter.

The key and value parameters are generic over the trait ToString, allowing a polymorphic behavior.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_param("integer", 42).unwrap();
params.add_param("string", "hello").unwrap();
source

pub fn add_str(&mut self, key: &str, value: &str) -> Result<(), Error>

Add a string parameter to the parameter.

§Notes
  • This method exists for parity with a C++ interface and is a less flexible version of add_param(), which application should use instead.
source

pub fn add_strit<I, S>(&mut self, key: &str, c: I) -> Result<(), Error>
where I: IntoIterator<Item = S>, S: AsRef<str>,

Add parameter where the value is generated from an iterator over strings, where entries are comma-separated.

§Examples
use std::collections::HashSet;
use blather::Params;

let mut params = Params::new();

params.add_strit("Cat", &["meow", "paws", "tail"]).unwrap();
assert_eq!(params.get_str("Cat"), Some("meow,paws,tail"));

let v = vec!["meow", "paws", "tail"];
params.add_strit("CatToo", v.into_iter()).unwrap();
assert_eq!(params.get_str("CatToo"), Some("meow,paws,tail"));

let mut hs = HashSet::new();
hs.insert("Elena");
hs.insert("Drake");
params.add_strit("Uncharted", hs.into_iter()).unwrap();
source

pub fn add_bool<K: ToString>( &mut self, key: K, value: bool ) -> Result<(), Error>

Add a boolean parameter.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_bool("should_be_true", true).unwrap();
params.add_bool("should_be_false", false).unwrap();
assert_eq!(params.get_bool("should_be_true"), Ok(true));
assert_eq!(params.get_bool("should_be_false"), Ok(false));
§Notes
  • Applications should not make assumptions about the specific string value added by this function. Do not treat boolean values as strings; use the get_bool() method instead.
source

pub fn have(&self, key: &str) -> bool

Returns true if the parameter with key exists. Returns false otherwise.

source

pub fn get_param<T: FromStr>(&self, key: &str) -> Result<T, Error>

Get a parameter and convert it to a requested type, fail if key isn’t found.

§Examples
use blather::{Params, Error};

let mut params = Params::new();
params.add_param("arthur", 42);
let fourtytwo = params.get_param::<u32>("arthur").unwrap();
assert_eq!(fourtytwo, 42);
let nonexist = params.get_param::<u32>("ford");
assert_eq!(nonexist, Err(Error::KeyNotFound("ford".to_string())));
source

pub fn get_param_def<T: FromStr>(&self, key: &str, def: T) -> Result<T, Error>

Get a parameter and convert it to a requested type, return a default value if key isn’t found.

§Examples
use blather::Params;

let mut params = Params::new();
let val = params.get_param_def::<u32>("nonexist", 11);
assert_eq!(val, Ok(11));
source

pub fn get_str(&self, key: &str) -> Option<&str>

Get string representation of a value for a requested key. Returns None if the key is not found in the inner storage. Returns Some(&str) if parameter exists.

source

pub fn get_str_def<'a>(&'a self, key: &str, def: &'a str) -> &'a str

Get string representation of a value for a requested key. Returns a default value if key does not exist in parameter buffer.

§Examples
use blather::Params;

let params = Params::new();
let e = params.get_str_def("nonexist", "elena");
assert_eq!(e, "elena");
source

pub fn get_int<T: FromStr>(&self, key: &str) -> Result<T, Error>

Get a parameter and convert it to an integer type.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_param("Num", 7);
assert_eq!(params.get_int::<usize>("Num").unwrap(), 7);
§Notes
  • This method exists primarily to achive some sort of parity with a corresponding C++ library. It is recommended that applications use Params::get_param() instead.
source

pub fn get_int_def<T: FromStr>(&self, key: &str, def: T) -> Result<T, Error>

Try to get the value of a key and interpret it as an integer. If the key does not exist then return a default value supplied by the caller.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_param("num", 11);
assert_eq!(params.get_int_def::<u32>("num", 5).unwrap(), 11);
assert_eq!(params.get_int_def::<u32>("nonexistent", 17).unwrap(), 17);
§Notes
source

pub fn get_bool(&self, key: &str) -> Result<bool, Error>

Get a boolean value; return error if key wasn’t found.

source

pub fn get_bool_def(&self, key: &str, def: bool) -> Result<bool, Error>

Get a boolean value; return a default value if key wasn’t found.

source

pub fn get_strvec(&self, key: &str) -> Result<Vec<String>, Error>

Parse the value of a key as a comma-separated list of strings and return it. Only non-empty entries are returned.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_param("csv", "elena,chloe,drake");
let sv = params.get_strvec("csv").unwrap();
assert_eq!(sv, vec!["elena", "chloe", "drake"]);
source

pub fn get_hashset(&self, key: &str) -> Result<HashSet<String>, Error>

Parse the value of a key as a comma-separated list of uniqie strings and return them in a HashSet. Only non-empty entries are returned.

§Examples
use blather::Params;

let mut params = Params::new();
params.add_param("set", "elena,chloe");
let set = params.get_hashset("set").unwrap();
assert_eq!(set.len(), 2);
assert_eq!(set.contains("elena"), true);
assert_eq!(set.contains("chloe"), true);
assert_eq!(set.contains("drake"), false);
source

pub fn calc_buf_size(&self) -> usize

Calculate the size of the buffer in serialized form. Each entry will be a newline terminated utf-8 line. Last line will be a single newline character.

source

pub fn serialize(&self) -> Result<Vec<u8>, Error>

Serialize Params buffer into a vector of bytes for transmission.

source

pub fn encoder_write(&self, buf: &mut BytesMut) -> Result<(), Error>

Write the Params to a buffer.

source

pub fn into_inner(self) -> HashMap<String, String>

Consume the Params buffer and return its internal HashMap.

Trait Implementations§

source§

impl Clone for Params

source§

fn clone(&self) -> Params

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl Debug for Params

source§

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

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

impl Default for Params

source§

fn default() -> Params

Returns the “default value” for a type. Read more
source§

impl Display for Params

source§

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

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

impl Encoder<&Params> for Codec

§

type Error = Error

The type of encoding errors. Read more
source§

fn encode(&mut self, params: &Params, buf: &mut BytesMut) -> Result<(), Error>

Encodes a frame into the buffer provided. Read more
source§

impl From<HashMap<String, String>> for Params

source§

fn from(hm: HashMap<String, String>) -> Self

Converts to this type from the input type.
source§

impl From<Params> for Telegram

source§

fn from(params: Params) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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,

§

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> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

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

§

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>,

§

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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more