Debian Codegraph @

third_party/rust/sfv/src/lib.rs

raw
1 /*!
2 `sfv` crate is an implementation of *Structured Field Values for HTTP* as specified in [RFC 8941](https://httpwg.org/specs/rfc8941.html) for parsing and serializing HTTP field values.
3 It also exposes a set of types that might be useful for defining new structured fields.
4
5 # Data Structures
6
7 There are three types of structured fields:
8
9 - `Item` - can be an `Integer`, `Decimal`, `String`, `Token`, `Byte Sequence`, or `Boolean`. It can have associated `Parameters`.
10 - `List` - array of zero or more members, each of which can be an `Item` or an `InnerList`, both of which can be `Parameterized`.
11 - `Dictionary` - ordered map of name-value pairs, where the names are short textual strings and the values are `Items` or arrays of `Items` (represented with `InnerList`), both of which can be `Parameterized`. There can be zero or more members, and their names are unique in the scope of the `Dictionary` they occur within.
12
13 There's also a few primitive types used to construct structured field values:
14 - `BareItem` used as `Item`'s value or as a parameter value in `Parameters`.
15 - `Parameters` are an ordered map of key-value pairs that are associated with an `Item` or `InnerList`. The keys are unique within the scope the `Parameters` they occur within, and the values are `BareItem`.
16 - `InnerList` is an array of zero or more `Items`. Can have `Parameters`.
17 - `ListEntry` represents either `Item` or `InnerList` as a member of `List` or as member-value in `Dictionary`.
18
19 # Examples
20
21 ### Parsing
22
23 ```
24 use sfv::Parser;
25
26 // Parsing structured field value of Item type.
27 let item_header_input = "12.445;foo=bar";
28 let item = Parser::parse_item(item_header_input.as_bytes());
29 assert!(item.is_ok());
30 println!("{:#?}", item);
31
32 // Parsing structured field value of List type.
33 let list_header_input = "1;a=tok, (\"foo\" \"bar\");baz, ()";
34 let list = Parser::parse_list(list_header_input.as_bytes());
35 assert!(list.is_ok());
36 println!("{:#?}", list);
37
38 // Parsing structured field value of Dictionary type.
39 let dict_header_input = "a=?0, b, c; foo=bar, rating=1.5, fruits=(apple pear)";
40 let dict = Parser::parse_dictionary(dict_header_input.as_bytes());
41 assert!(dict.is_ok());
42 println!("{:#?}", dict);
43 ```
44
45 ### Getting Parsed Value Members
46 ```
47 use sfv::*;
48
49 let dict_header = "u=2, n=(* foo 2)";
50 let dict = Parser::parse_dictionary(dict_header.as_bytes()).unwrap();
51
52 // Case 1 - handling value if it's an Item of Integer type
53 let u_val = match dict.get("u") {
54 Some(ListEntry::Item(item)) => item.bare_item.as_int(),
55 _ => None,
56 };
57
58 if let Some(u_val) = u_val {
59 println!("{}", u_val);
60 }
61
62 // Case 2 - matching on all possible types
63 match dict.get("u") {
64 Some(ListEntry::Item(item)) => match &item.bare_item {
65 BareItem::Token(val) => {
66 // do something if it's a Token
67 println!("{}", val);
68 }
69 BareItem::Integer(val) => {
70 // do something if it's an Integer
71 println!("{}", val);
72 }
73 BareItem::Boolean(val) => {
74 // do something if it's a Boolean
75 println!("{}", val);
76 }
77 BareItem::Decimal(val) => {
78 // do something if it's a Decimal
79 println!("{}", val);
80 }
81 BareItem::String(val) => {
82 // do something if it's a String
83 println!("{}", val);
84 }
85 BareItem::ByteSeq(val) => {
86 // do something if it's a ByteSeq
87 println!("{:?}", val);
88 }
89 },
90 Some(ListEntry::InnerList(inner_list)) => {
91 // do something if it's an InnerList
92 println!("{:?}", inner_list.items);
93 }
94 None => panic!("key not found"),
95 }
96 ```
97
98 ### Structured Field Value Construction and Serialization
99 Creates `Item` with empty parameters:
100 ```
101 use sfv::{Item, BareItem, SerializeValue};
102
103 let str_item = Item::new(BareItem::String(String::from("foo")));
104 assert_eq!(str_item.serialize_value().unwrap(), "\"foo\"");
105 ```
106
107
108 Creates `Item` field value with parameters:
109 ```
110 use sfv::{Item, BareItem, SerializeValue, Parameters, Decimal, FromPrimitive};
111
112 let mut params = Parameters::new();
113 let decimal = Decimal::from_f64(13.45655).unwrap();
114 params.insert("key".into(), BareItem::Decimal(decimal));
115 let int_item = Item::with_params(BareItem::Integer(99), params);
116 assert_eq!(int_item.serialize_value().unwrap(), "99;key=13.457");
117 ```
118
119 Creates `List` field value with `Item` and parametrized `InnerList` as members:
120 ```
121 use sfv::{Item, BareItem, InnerList, List, SerializeValue, Parameters};
122
123 let tok_item = BareItem::Token("tok".into());
124
125 // Creates Item.
126 let str_item = Item::new(BareItem::String(String::from("foo")));
127
128 // Creates InnerList members.
129 let mut int_item_params = Parameters::new();
130 int_item_params.insert("key".into(), BareItem::Boolean(false));
131 let int_item = Item::with_params(BareItem::Integer(99), int_item_params);
132
133 // Creates InnerList.
134 let mut inner_list_params = Parameters::new();
135 inner_list_params.insert("bar".into(), BareItem::Boolean(true));
136 let inner_list = InnerList::with_params(vec![int_item, str_item], inner_list_params);
137
138
139 let list: List = vec![Item::new(tok_item).into(), inner_list.into()];
140 assert_eq!(
141 list.serialize_value().unwrap(),
142 "tok, (99;key=?0 \"foo\");bar"
143 );
144 ```
145
146 Creates `Dictionary` field value:
147 ```
148 use sfv::{Parser, Item, BareItem, SerializeValue, ParseValue, Dictionary};
149
150 let member_value1 = Item::new(BareItem::String(String::from("apple")));
151 let member_value2 = Item::new(BareItem::Boolean(true));
152 let member_value3 = Item::new(BareItem::Boolean(false));
153
154 let mut dict = Dictionary::new();
155 dict.insert("key1".into(), member_value1.into());
156 dict.insert("key2".into(), member_value2.into());
157 dict.insert("key3".into(), member_value3.into());
158
159 assert_eq!(
160 dict.serialize_value().unwrap(),
161 "key1=\"apple\", key2, key3=?0"
162 );
163
164 ```
165 */
166
167 mod parser;
168 mod ref_serializer;
169 mod serializer;
170 mod utils;
171
172 #[cfg(test)]
173 mod test_parser;
174 #[cfg(test)]
175 mod test_serializer;
176 use indexmap::IndexMap;
177
178 pub use rust_decimal::{
179 prelude::{FromPrimitive, FromStr},
180 Decimal,
181 };
182
183 pub use parser::{ParseMore, ParseValue, Parser};
184 pub use ref_serializer::{RefDictSerializer, RefItemSerializer, RefListSerializer};
185 pub use serializer::SerializeValue;
186
187 type SFVResult<T> = std::result::Result<T, &'static str>;
188
189 /// Represents `Item` type structured field value.
190 /// Can be used as a member of `List` or `Dictionary`.
191 // sf-item = bare-item parameters
192 // bare-item = sf-integer / sf-decimal / sf-string / sf-token
193 // / sf-binary / sf-boolean
194 #[derive(Debug, PartialEq, Clone)]
195 pub struct Item {
196 /// Value of `Item`.
197 pub bare_item: BareItem,
198 /// `Item`'s associated parameters. Can be empty.
199 pub params: Parameters,
200 }
201
202 impl Item {
203 /// Returns new `Item` with empty `Parameters`.
204 pub fn new(bare_item: BareItem) -> Item {
205 Item {
206 bare_item,
207 params: Parameters::new(),
208 }
209 }
210 /// Returns new `Item` with specified `Parameters`.
211 pub fn with_params(bare_item: BareItem, params: Parameters) -> Item {
212 Item { bare_item, params }
213 }
214 }
215
216 /// Represents `Dictionary` type structured field value.
217 // sf-dictionary = dict-member *( OWS "," OWS dict-member )
218 // dict-member = member-name [ "=" member-value ]
219 // member-name = key
220 // member-value = sf-item / inner-list
221 pub type Dictionary = IndexMap<String, ListEntry>;
222
223 /// Represents `List` type structured field value.
224 // sf-list = list-member *( OWS "," OWS list-member )
225 // list-member = sf-item / inner-list
226 pub type List = Vec<ListEntry>;
227
228 /// Parameters of `Item` or `InnerList`.
229 // parameters = *( ";" *SP parameter )
230 // parameter = param-name [ "=" param-value ]
231 // param-name = key
232 // key = ( lcalpha / "*" )
233 // *( lcalpha / DIGIT / "_" / "-" / "." / "*" )
234 // lcalpha = %x61-7A ; a-z
235 // param-value = bare-item
236 pub type Parameters = IndexMap<String, BareItem>;
237
238 /// Represents a member of `List` or `Dictionary` structured field value.
239 #[derive(Debug, PartialEq, Clone)]
240 pub enum ListEntry {
241 /// Member of `Item` type.
242 Item(Item),
243 /// Member of `InnerList` (array of `Items`) type.
244 InnerList(InnerList),
245 }
246
247 impl From<Item> for ListEntry {
248 fn from(item: Item) -> Self {
249 ListEntry::Item(item)
250 }
251 }
252
253 impl From<InnerList> for ListEntry {
254 fn from(item: InnerList) -> Self {
255 ListEntry::InnerList(item)
256 }
257 }
258
259 /// Array of `Items` with associated `Parameters`.
260 // inner-list = "(" *SP [ sf-item *( 1*SP sf-item ) *SP ] ")"
261 // parameters
262 #[derive(Debug, PartialEq, Clone)]
263 pub struct InnerList {
264 /// `Items` that `InnerList` contains. Can be empty.
265 pub items: Vec<Item>,
266 /// `InnerList`'s associated parameters. Can be empty.
267 pub params: Parameters,
268 }
269
270 impl InnerList {
271 /// Returns new `InnerList` with empty `Parameters`.
272 pub fn new(items: Vec<Item>) -> InnerList {
273 InnerList {
274 items,
275 params: Parameters::new(),
276 }
277 }
278
279 /// Returns new `InnerList` with specified `Parameters`.
280 pub fn with_params(items: Vec<Item>, params: Parameters) -> InnerList {
281 InnerList { items, params }
282 }
283 }
284
285 /// `BareItem` type is used to construct `Items` or `Parameters` values.
286 #[derive(Debug, PartialEq, Clone)]
287 pub enum BareItem {
288 /// Decimal number
289 // sf-decimal = ["-"] 1*12DIGIT "." 1*3DIGIT
290 Decimal(Decimal),
291 /// Integer number
292 // sf-integer = ["-"] 1*15DIGIT
293 Integer(i64),
294 // sf-string = DQUOTE *chr DQUOTE
295 // chr = unescaped / escaped
296 // unescaped = %x20-21 / %x23-5B / %x5D-7E
297 // escaped = "\" ( DQUOTE / "\" )
298 String(String),
299 // ":" *(base64) ":"
300 // base64 = ALPHA / DIGIT / "+" / "/" / "="
301 ByteSeq(Vec<u8>),
302 // sf-boolean = "?" boolean
303 // boolean = "0" / "1"
304 Boolean(bool),
305 // sf-token = ( ALPHA / "*" ) *( tchar / ":" / "/" )
306 Token(String),
307 }
308
309 impl BareItem {
310 /// If `BareItem` is a decimal, returns `Decimal`, otherwise returns `None`.
311 /// ```
312 /// # use sfv::{BareItem, Decimal, FromPrimitive};
313 /// let decimal_number = Decimal::from_f64(415.566).unwrap();
314 /// let bare_item: BareItem = decimal_number.into();
315 /// assert_eq!(bare_item.as_decimal().unwrap(), decimal_number);
316 /// ```
317 pub fn as_decimal(&self) -> Option<Decimal> {
318 match *self {
319 BareItem::Decimal(val) => Some(val),
320 _ => None,
321 }
322 }
323 /// If `BareItem` is an integer, returns `i64`, otherwise returns `None`.
324 /// ```
325 /// # use sfv::BareItem;
326 /// let bare_item: BareItem = 100.into();
327 /// assert_eq!(bare_item.as_int().unwrap(), 100);
328 /// ```
329 pub fn as_int(&self) -> Option<i64> {
330 match *self {
331 BareItem::Integer(val) => Some(val),
332 _ => None,
333 }
334 }
335 /// If `BareItem` is `String`, returns `&str`, otherwise returns `None`.
336 /// ```
337 /// # use sfv::BareItem;
338 /// let bare_item = BareItem::String("foo".into());
339 /// assert_eq!(bare_item.as_str().unwrap(), "foo");
340 /// ```
341 pub fn as_str(&self) -> Option<&str> {
342 match *self {
343 BareItem::String(ref val) => Some(val),
344 _ => None,
345 }
346 }
347 /// If `BareItem` is a `ByteSeq`, returns `&Vec<u8>`, otherwise returns `None`.
348 /// ```
349 /// # use sfv::BareItem;
350 /// let bare_item = BareItem::ByteSeq("foo".to_owned().into_bytes());
351 /// assert_eq!(bare_item.as_byte_seq().unwrap().as_slice(), "foo".as_bytes());
352 /// ```
353 pub fn as_byte_seq(&self) -> Option<&Vec<u8>> {
354 match *self {
355 BareItem::ByteSeq(ref val) => Some(val),
356 _ => None,
357 }
358 }
359 /// If `BareItem` is a `Boolean`, returns `bool`, otherwise returns `None`.
360 /// ```
361 /// # use sfv::{BareItem, Decimal, FromPrimitive};
362 /// let bare_item = BareItem::Boolean(true);
363 /// assert_eq!(bare_item.as_bool().unwrap(), true);
364 /// ```
365 pub fn as_bool(&self) -> Option<bool> {
366 match *self {
367 BareItem::Boolean(val) => Some(val),
368 _ => None,
369 }
370 }
371 /// If `BareItem` is a `Token`, returns `&str`, otherwise returns `None`.
372 /// ```
373 /// use sfv::BareItem;
374 ///
375 /// let bare_item = BareItem::Token("*bar".into());
376 /// assert_eq!(bare_item.as_token().unwrap(), "*bar");
377 /// ```
378 pub fn as_token(&self) -> Option<&str> {
379 match *self {
380 BareItem::Token(ref val) => Some(val),
381 _ => None,
382 }
383 }
384 }
385
386 impl From<i64> for BareItem {
387 /// Converts `i64` into `BareItem::Integer`.
388 /// ```
389 /// # use sfv::BareItem;
390 /// let bare_item: BareItem = 456.into();
391 /// assert_eq!(bare_item.as_int().unwrap(), 456);
392 /// ```
393 fn from(item: i64) -> Self {
394 BareItem::Integer(item)
395 }
396 }
397
398 impl From<Decimal> for BareItem {
399 /// Converts `Decimal` into `BareItem::Decimal`.
400 /// ```
401 /// # use sfv::{BareItem, Decimal, FromPrimitive};
402 /// let decimal_number = Decimal::from_f64(48.01).unwrap();
403 /// let bare_item: BareItem = decimal_number.into();
404 /// assert_eq!(bare_item.as_decimal().unwrap(), decimal_number);
405 /// ```
406 fn from(item: Decimal) -> Self {
407 BareItem::Decimal(item)
408 }
409 }
410
411 #[derive(Debug, PartialEq)]
412 pub(crate) enum Num {
413 Decimal(Decimal),
414 Integer(i64),
415 }
416
417 /// Similar to `BareItem`, but used to serialize values via `RefItemSerializer`, `RefListSerializer`, `RefDictSerializer`.
418 #[derive(Debug, PartialEq, Clone)]
419 pub enum RefBareItem<'a> {
420 Integer(i64),
421 Decimal(Decimal),
422 String(&'a str),
423 ByteSeq(&'a [u8]),
424 Boolean(bool),
425 Token(&'a str),
426 }
427
428 impl BareItem {
429 /// Converts `BareItem` into `RefBareItem`.
430 fn to_ref_bare_item(&self) -> RefBareItem {
431 match self {
432 BareItem::Integer(val) => RefBareItem::Integer(*val),
433 BareItem::Decimal(val) => RefBareItem::Decimal(*val),
434 BareItem::String(val) => RefBareItem::String(val),
435 BareItem::ByteSeq(val) => RefBareItem::ByteSeq(val.as_slice()),
436 BareItem::Boolean(val) => RefBareItem::Boolean(*val),
437 BareItem::Token(val) => RefBareItem::Token(val),
438 }
439 }
440 }