bencode_minimal/lib.rs
1mod decoder;
2mod encoder;
3mod into_str;
4mod try_from_value;
5mod value;
6
7pub use into_str::IntoStr;
8pub use try_from_value::TryFromValue;
9pub use value::{Dict, Int, List, Str, Value};
10
11/// Create a [Value::Int] from [i64]
12///
13/// ```rust
14/// use bencode_minimal::*;
15///
16/// let v = int!(42);
17/// assert_eq!(v, Value::Int(42));
18/// ```
19#[macro_export]
20macro_rules! int {
21 ($x:expr) => {
22 bencode_minimal::Value::Int($x)
23 };
24}
25
26/// Create a [Value::Str] from all things [IntoStr] ([&str], [String], &[[u8]], [Vec]<[u8]> etc.)`
27///
28/// Values will be borrowed or owned depending on the input type and pass by value/reference.
29///
30/// ```rust
31/// use bencode_minimal::*;
32/// use std::borrow::Cow;
33///
34/// let v = str!("hello");
35/// assert_eq!(v, Value::Str(Cow::Borrowed(b"hello")));
36///
37/// let v = str!("hello".to_string());
38/// assert_eq!(v, Value::Str(Cow::Owned(b"hello".to_vec())));
39///
40/// let v = str!(b"hello");
41/// assert_eq!(v, Value::Str(Cow::Borrowed(b"hello")));
42///
43/// let v = str!(b"world".to_vec());
44/// assert_eq!(v, Value::Str(Cow::Owned(b"world".to_vec())));
45/// ```
46#[macro_export]
47macro_rules! str {
48 ($x:expr) => {
49 bencode_minimal::Value::Str(bencode_minimal::IntoStr::into_str($x))
50 };
51}
52
53/// Create a [Value::List] from a list of [Value]s
54///
55/// ```rust
56/// use bencode_minimal::*;
57/// use std::borrow::Cow;
58///
59/// let v = list![
60/// int!(42),
61/// str!("hello"),
62/// ];
63/// assert_eq!(v, Value::List(vec![Value::Int(42), Value::Str(Cow::Borrowed(b"hello"))]));
64/// ```
65#[macro_export]
66macro_rules! list {
67 ($($x:expr),* $(,)?) => {
68 bencode_minimal::Value::List(vec![$($x),*])
69 }
70}
71
72/// Create a [Value::Dict] from key-value pairs (keys like [str!], values as [Value]s)
73///
74/// ```rust
75/// use bencode_minimal::*;
76/// use std::borrow::Cow;
77/// let v = dict! {
78/// "age" => int!(42),
79/// "name" => str!("John"),
80/// };
81/// assert_eq!(v, Value::Dict([
82/// (Cow::Borrowed(b"age".as_ref()), Value::Int(42)),
83/// (Cow::Borrowed(b"name".as_ref()), Value::Str(Cow::Borrowed(b"John"))),
84/// ].into_iter().collect()));
85/// ```
86#[macro_export]
87macro_rules! dict {
88 ($($k:expr => $v:expr),* $(,)?) => {
89 bencode_minimal::Value::Dict([$((bencode_minimal::IntoStr::into_str($k), $v)),*].into_iter().collect())
90 };
91 () => {
92 bencode_minimal::Value::Dict(std::collections::BTreeMap::new())
93 };
94}