Debian Codegraph @

README.md

raw symbols SCIP
1 # Bendy
2
3 [![Build Status](https://travis-ci.org/P3KI/bendy.svg?branch=master)](https://travis-ci.org/P3KI/bendy)
4 [![Current Version](https://meritbadge.herokuapp.com/bendy)](https://crates.io/crates/bendy)
5 [![License: BSD-3-Clause](https://img.shields.io/github/license/P3KI/bendy.svg)](https://github.com/P3KI/bendy/blob/master/LICENSE-BSD3)
6
7 A Rust library for encoding and decoding bencode with enforced canonicalization rules.
8 It also provides some facilities for reflecting over arbitrary decoded bencode structures.
9 [Bencode](https://en.wikipedia.org/wiki/Bencode) is a simple but very effective encoding
10 scheme, originating with the BitTorrent peer-to-peer system.
11
12 ---
13
14 You may be looking for:
15
16 - [Known Alternatives](#known-alternatives)
17 - [Why should I use it](#why-should-i-use-it)
18 - [Usage](#usage)
19 - [Feature Flags](#feature-flags)
20 - [Encoding](#encoding-with-tobencode)
21 - [Decoding](#decoding-with-frombencode)
22 - [Serde Support](#serde-support)
23 - [Reflection](#reflection)
24 - [Unsafe Code](#usage-of-unsafe-code)
25 - [Contributing](#contributing)
26
27 ---
28
29 ## Known alternatives:
30 This is not the first library to implement Bencode. In fact there are several
31 implementations already:
32
33 - Toby Padilla [serde-bencode](https://github.com/toby/serde-bencode)
34 - Arjan Topolovec's [rust-bencode](https://github.com/arjantop/rust-bencode),
35 - Murarth's [bencode](https://github.com/murarth/bencode),
36 - and Jonas Hermsmeier's [rust-bencode](https://github.com/jhermsmeier/rust-bencode)
37
38 ## Why should I use it?
39 So why the extra work adding yet-another-version of a thing that already exists, you
40 might ask?
41
42 ### Enforced correctness
43 Implementing a canonical encoding form is straight forward. It comes down to defining
44 *a proper way of handling unordered data*. The next step is that bendy's sorting data
45 before encoding it using the regular Bencode rules. If your data is already sorted bendy
46 will of course skip the extra sorting step to gain efficiency.
47 But bendy goes a step further to *ensure correctness*: If you hand the library data that
48 you say is already sorted, bendy still does an in-place verification to *ensure that your
49 data actually is sorted* and complains if it isn't. In the end, once bendy serialized
50 your data, it's Bencode through and through. So it's perfectly compatible with every
51 other Bencode library.
52
53 Just remember: At this point *only bendy* enforces the correctness of the canonical
54 format if you read it back in.
55
56 ### Canonical representation
57 Bendy ensures that any de-serialize / serialize round trip produces the exact *same*
58 and *correct* binary representation. This is relevant if you're dealing with unordered
59 sets or map-structured data where theoretically the order is not relevant, but in
60 practice it is, especially if you want to ensure that cryptographic signatures related
61 to the data structure do not get invalidated accidentally.
62
63 | Data Structure | Default Impl | Comment |
64 |----------------|--------------|--------------------------------------------------------------------------------------------|
65 | Vec | ✔ | Defines own ordering |
66 | VecDeque | ✔ | Defines own ordering |
67 | LinkedList | ✔ | Defines own ordering |
68 | HashMap | ✔ | Ordering missing but content is ordered by key byte representation. |
69 | BTreeMap | ✔ | Defines own ordering |
70 | HashSet | ✘ | (Unordered) Set handling not yet defined |
71 | BTreeSet | ✘ | (Unordered) Set handling not yet defined |
72 | BinaryHeap | ✘ | Ordering missing |
73 | Iterator | ~ | `emit_unchecked_list()` allows to emit any iterable but user needs to ensure the ordering. |
74
75 **Attention:**
76
77 - Since most list types already define their inner ordering, data structures
78 like `Vec`, `VecDeque`, and `LinkedList` will not get sorted during encoding!
79
80 - There is no default implementation for handling generic iterators.
81 This is by design. `Bendy` cannot tell from an iterator whether the underlying
82 structure requires sorting or not and would have to take data as-is.
83
84 ## Usage
85
86 First you need to add bendy as a project dependency:
87
88 ```toml
89 [dependencies]
90 bendy = "^0.4"
91 ```
92
93 ### Feature flags
94
95 Bendy has the following feature flags:
96 * `std` - Enabled by default.
97 * `serde` - Support serde. Requires `std` to be enabled.
98 * `inspect` - Include reflection facilities.
99
100 ### Encoding with `ToBencode`
101
102 To encode an object of a type which already implements the `ToBencode` trait
103 it is enough to import the trait and call the `to_bencode()` function on the object.
104
105 ```rust
106 use bendy::encoding::{ToBencode, Error};
107
108 let my_data = vec!["hello", "world"];
109 let encoded = my_data.to_bencode()?;
110
111 assert_eq!(b"l5:hello5:worlde", encoded.as_slice());
112
113 Ok::<(), Error>(())
114 ```
115
116 ### Implementing `ToBencode`
117
118 In most cases it should be enough to overwrite the associated `encode` function
119 and keep the default implementation of `to_bencode`.
120
121 The function will provide you with a `SingleItemEncoder` which must be used to
122 emit any relevant components of the current object. As long as these implement
123 `ToBencode` themselves it is enough to pass them into the `emit` function of
124 the encoder as this will serialize any type implementing the trait.
125
126 Next to `emit` the encoder also provides a list of functions to encode specific
127 bencode primitives (i.e. `emit_int` and `emit_str`) and nested bencode elements
128 (i.e. `emit_dict` and `emit_list`). These methods should be used if its necessary
129 to output a specific non default data type.
130
131 **Implementing Integer Encoding**
132
133 As bencode has native integer support bendy provides default implementations for
134 all of rusts native integer types. This allows to call `to_bencode` on any integer
135 object and to pass these objects into the encoder's `emit_int` function.
136
137 ```rust
138 use bendy::encoding::{ToBencode, SingleItemEncoder, Error};
139
140 struct IntegerWrapper(i64);
141
142 impl ToBencode for IntegerWrapper {
143 const MAX_DEPTH: usize = 0;
144
145 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
146 encoder.emit_int(self.0)
147 }
148 }
149
150 let example = IntegerWrapper(21);
151
152 let encoded = example.to_bencode()?;
153 assert_eq!(b"i21e", encoded.as_slice());
154
155 let encoded = 21.to_bencode()?;
156 assert_eq!(b"i21e", encoded.as_slice());
157
158 Ok::<(), Error>(())
159 ```
160
161 **Encode a byte string**
162
163 Another data type bencode natively supports are byte strings. Therefore bendy
164 provides default implementations for `String` and `&str`.
165
166 ```rust
167 use bendy::encoding::{ToBencode, SingleItemEncoder, Error};
168
169 struct StringWrapper(String);
170
171 impl ToBencode for StringWrapper {
172 const MAX_DEPTH: usize = 0;
173
174 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
175 encoder.emit_str(&self.0)
176 }
177 }
178
179 let example = StringWrapper("content".to_string());
180
181 let encoded = example.to_bencode()?;
182 assert_eq!(b"7:content", encoded.as_slice());
183
184 let encoded = "content".to_bencode()?;
185 assert_eq!(b"7:content", encoded.as_slice());
186
187 Ok::<(), Error>(())
188 ```
189
190 As its a very common pattern to represent a byte string as `Vec<u8>` bendy
191 exposes the `AsString` wrapper. This can be used to encapsulate any element
192 implementing `AsRef<[u8]>` to output itself as a bencode string instead of a
193 list.
194
195 ```rust
196 use bendy::encoding::{ToBencode, SingleItemEncoder, Error, AsString};
197
198 struct ByteStringWrapper(Vec<u8>);
199
200 impl ToBencode for ByteStringWrapper {
201 const MAX_DEPTH: usize = 0;
202
203 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
204 let content = AsString(&self.0);
205 encoder.emit(&content)
206 }
207 }
208
209 let example = ByteStringWrapper(b"content".to_vec());
210
211 let encoded = example.to_bencode()?;
212 assert_eq!(b"7:content", encoded.as_slice());
213
214 let encoded = AsString(b"content").to_bencode()?;
215 assert_eq!(b"7:content", encoded.as_slice());
216
217 Ok::<(), Error>(())
218 ```
219
220 **Encode a dictionary**
221
222 If a data structure contains key-value pairs its most likely a good idea to
223 encode it as a bencode dictionary. This is also true for most structs with
224 more then one member as it might be helpful to represent their names to ensure
225 the existence of specific (optional) member.
226
227 __Attention:__ To ensure a canonical representation bendy requires that the keys
228 of a dictionary emitted via `emit_dict` are sorted in ascending order or the
229 encoding will fail with an error of kind `UnsortedKeys`. In case of an unsorted
230 dictionary it might be useful to use `emit_and_sort_dict` instead.
231
232 ```rust
233 use bendy::encoding::{ToBencode, SingleItemEncoder, Error};
234
235 struct Example {
236 label: String,
237 counter: u64,
238 }
239
240 impl ToBencode for Example {
241 const MAX_DEPTH: usize = 1;
242
243 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
244 encoder.emit_dict(|mut e| {
245 e.emit_pair(b"counter", &self.counter)?;
246 e.emit_pair(b"label", &self.label)?;
247
248 Ok(())
249 })
250 }
251 }
252
253 let example = Example { label: "Example".to_string(), counter: 0 };
254
255 let encoded = example.to_bencode()?;
256 assert_eq!(b"d7:counteri0e5:label7:Examplee", encoded.as_slice());
257
258 Ok::<(), Error>(())
259 ```
260
261 **Encode a list**
262
263 While encoding a list bendy assumes the elements inside this list are
264 inherently sorted through their position inside the list. The implementation
265 is therefore free to choose its own sorting.
266
267 ```rust
268 use bendy::encoding::{ToBencode, SingleItemEncoder, Error};
269
270 struct Location(i64, i64);
271
272 impl ToBencode for Location {
273 const MAX_DEPTH: usize = 1;
274
275 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
276 encoder.emit_list(|e| {
277 e.emit_int(self.0)?;
278 e.emit_int(self.1)
279 })
280 }
281 }
282
283 let example = Location(2, 3);
284
285 let encoded = example.to_bencode()?;
286 assert_eq!(b"li2ei3ee", encoded.as_slice());
287
288 Ok::<(), Error>(())
289 ```
290
291 ### Decoding with `FromBencode`
292
293 To decode an object of a type which already implements the `FromBencode` trait
294 it is enough to import the trait and call the `from_bencode()` function on the object.
295
296 ```rust
297 use bendy::decoding::{FromBencode, Error};
298
299 let encoded = b"l5:hello5:worlde".to_vec();
300 let decoded = Vec::<String>::from_bencode(&encoded)?;
301
302 assert_eq!(vec!["hello", "world"], decoded);
303
304 Ok::<(), Error>(())
305 ```
306
307 ### Implementing `FromBencode`
308
309 In most cases it should be enough to overwrite the associated
310 `decode_bencode_object` function and keep the default implementation of
311 `from_bencode`.
312
313 The function will provide you with an representation of a bencode `Object`
314 which must be processed to receive any relevant components of the expected data
315 type. As long as these implement `FromBencode` themselves it is enough to call
316 `decode_bencode_object` on the expected data type of the element as this will
317 deserialize any type implementing the trait.
318
319 Next to `from_bencode` the bencode `Object` representation also provides a list
320 of helper functions to itself into specific bencode primitives and container
321 (i.e. `bytes_or`, `integer_or_else` or `try_into_list`). Which than can be used
322 to restore the actual element.
323
324 **Decode an integer**
325
326 As bencode has native integer support bendy provides default implementations
327 for all of rusts native integer types. This allows to call `from_bencode` on
328 any type of integer.
329
330 *Attention:* If it's necessary to handle a big integer which has no
331 representation through one of the default data types it's always possible to
332 access the string version of the number during decoding.
333
334 ```rust
335 use bendy::decoding::{FromBencode, Object, Error};
336
337 #[derive(Debug, Eq, PartialEq)]
338 struct IntegerWrapper(i64);
339
340 impl FromBencode for IntegerWrapper {
341 const EXPECTED_RECURSION_DEPTH: usize = 0;
342
343 fn decode_bencode_object(object: Object) -> Result<Self, Error> {
344 // This is an example for content handling. It would also be possible
345 // to call `i64::decode_bencode_object(object)` directly.
346 let content = object.try_into_integer()?;
347 let number = content.parse::<i64>()?;
348
349 Ok(IntegerWrapper(number))
350 }
351 }
352
353 let encoded = b"i21e".to_vec();
354
355 let example = IntegerWrapper::from_bencode(&encoded)?;
356 assert_eq!(IntegerWrapper(21), example);
357
358 let example = i64::from_bencode(&encoded)?;
359 assert_eq!(21, example);
360
361 Ok::<(), Error>(())
362 ```
363
364 **Decode a byte string**
365
366 In most cases it is possible to restore a string from its bencode
367 representation as a byte sequence via the `String::from_utf8` and
368 `str::from_utf8`.
369
370 ```rust
371 use bendy::decoding::{FromBencode, Object, Error};
372
373 #[derive(Debug, Eq, PartialEq)]
374 struct StringWrapper(String);
375
376 impl FromBencode for StringWrapper {
377 const EXPECTED_RECURSION_DEPTH: usize = 0;
378
379 fn decode_bencode_object(object: Object) -> Result<Self, Error> {
380 // This is an example for content handling. It would also be possible
381 // to call `String::decode_bencode_object(object)` directly.
382 let content = object.try_into_bytes()?;
383 let content = String::from_utf8(content.to_vec())?;
384
385 Ok(StringWrapper(content))
386 }
387 }
388
389 let encoded = b"7:content".to_vec();
390
391 let example = StringWrapper::from_bencode(&encoded)?;
392 assert_eq!(StringWrapper("content".to_string()), example);
393
394 let example = String::from_bencode(&encoded)?;
395 assert_eq!("content".to_string(), example);
396
397 Ok::<(), Error>(())
398 ```
399
400 If the content is a non utf8 encoded string or an actual byte sequence the
401 `AsString` wrapper might be useful to restore the bencode string object as
402 a sequence of bytes through an object of type `Vec<u8>`.
403
404 ```rust
405 use bendy::{
406 decoding::{FromBencode, Object, Error},
407 encoding::AsString,
408 };
409
410 #[derive(Debug, Eq, PartialEq)]
411 struct ByteStringWrapper(Vec<u8>);
412
413 impl FromBencode for ByteStringWrapper {
414 const EXPECTED_RECURSION_DEPTH: usize = 0;
415
416 fn decode_bencode_object(object: Object) -> Result<Self, Error> {
417 let content = AsString::decode_bencode_object(object)?;
418 Ok(ByteStringWrapper(content.0))
419 }
420 }
421
422 let encoded = b"7:content".to_vec();
423
424 let example = ByteStringWrapper::from_bencode(&encoded)?;
425 assert_eq!(ByteStringWrapper(b"content".to_vec()), example);
426
427 let example = AsString::from_bencode(&encoded)?;
428 assert_eq!(b"content".to_vec(), example.0);
429
430 Ok::<(), Error>(())
431 ```
432
433 **Decode a dictionary**
434
435 Unwrapping the bencode object into a dictionary will provide a dictionary
436 decoder which can be used to access the included key-value pairs.
437
438 To improve the error handling in case of huge or multiple nested dictionaries
439 the decoding module provides a `ResultExt` trait which allows to add a context
440 description in case of an error. If multiple context calls are nested they will
441 concatenated in a dot notation like style.
442
443 ```rust
444 use bendy::decoding::{FromBencode, Object, Error, ResultExt};
445
446 #[derive(Debug, Eq, PartialEq)]
447 struct Example {
448 label: String,
449 counter: u64,
450 }
451
452 impl FromBencode for Example {
453 const EXPECTED_RECURSION_DEPTH: usize = 1;
454
455 fn decode_bencode_object(object: Object) -> Result<Self, Error> {
456 let mut counter = None;
457 let mut label = None;
458
459 let mut dict = object.try_into_dictionary()?;
460 while let Some(pair) = dict.next_pair()? {
461 match pair {
462 (b"counter", value) => {
463 counter = u64::decode_bencode_object(value)
464 .context("counter")
465 .map(Some)?;
466 },
467 (b"label", value) => {
468 label = String::decode_bencode_object(value)
469 .context("label")
470 .map(Some)?;
471 },
472 (unknown_field, _) => {
473 return Err(Error::unexpected_field(String::from_utf8_lossy(
474 unknown_field,
475 )));
476 },
477 }
478 }
479
480 let counter = counter.ok_or_else(|| Error::missing_field("counter"))?;
481 let label= label.ok_or_else(|| Error::missing_field("label"))?;
482
483 Ok(Example { counter, label })
484 }
485 }
486
487 let encoded = b"d7:counteri0e5:label7:Examplee".to_vec();
488 let expected = Example { label: "Example".to_string(), counter: 0 };
489
490 let example = Example::from_bencode(&encoded)?;
491 assert_eq!(expected, example);
492
493 Ok::<(), Error>(())
494 ```
495
496 **Decode a list**
497
498 Unwrapping the bencode object into a list will provide a list decoder which can
499 be used to access the contained elements.
500
501 ```rust
502 use bendy::decoding::{FromBencode, Object, Error};
503
504 #[derive(Debug, PartialEq, Eq)]
505 struct Location(i64, i64);
506
507 impl FromBencode for Location {
508 const EXPECTED_RECURSION_DEPTH: usize = 1;
509
510 fn decode_bencode_object(object: Object) -> Result<Self, Error> {
511 let mut list = object.try_into_list()?;
512
513 let x = list.next_object()?.ok_or(Error::missing_field("x"))?;
514 let x = i64::decode_bencode_object(x)?;
515
516 let y = list.next_object()?.ok_or(Error::missing_field("y"))?;
517 let y = i64::decode_bencode_object(y)?;
518
519 Ok(Location(x, y))
520 }
521 }
522
523 let encoded = b"li2ei3ee".to_vec();
524 let expected = Location(2, 3);
525
526 let example = Location::from_bencode(&encoded)?;
527 assert_eq!(expected, example);
528
529 Ok::<(), Error>(())
530 ```
531
532 ### Optional: Limitation of recursive parsing
533
534 **What?**
535
536 The library allows to set an expected recursion depth limit for de- and encoding.
537 If set, the parser will use this value as an upper limit for the validation of any nested
538 data structure and abort with an error if an additional level of nesting is detected.
539
540 While the encoding limit itself is primarily there to increase the confidence of bendy
541 users in their own validation code, the decoding limit should be used to avoid
542 parsing of malformed or malicious external data.
543
544 - The encoding limit can be set through the `MAX_DEPTH` constant in any implementation
545 of the `ToBencode` trait.
546 - The decoding limit can be set through the `EXPECTED_RECURSION_DEPTH` constant in any
547 implementation of the `FromBencode` trait.
548
549 **How?**
550
551 The nesting level calculation always starts on level zero, is incremented by one when
552 the parser enters a nested bencode element (i.e. list, dictionary) and decrement as
553 soon as the related element ends. Therefore any values decoded as bencode strings
554 or integers do not affect the nesting limit.
555
556 ### Serde Support
557
558 Bendy supports serde when the `serde` feature is enabled:
559
560 ```toml
561 [dependencies]
562 bendy = { version = "^0.3", features = ["std", "serde"] }
563 serde = { version = "1.0", features = ["derive"] }
564 ```
565
566 With the feature enabled, values can be serialized to and deserialized from
567 bencode with `bendy::serde::from_bytes` and `bendy::serde::to_bytes`
568 respectively:
569
570
571 ```rust
572 # #[cfg(not(feature = "serde"))]
573 # fn main() {}
574 # #[cfg(feature = "serde")]
575 # fn main() -> Result<(), bendy::serde::Error> {
576
577 use serde_derive::{Deserialize, Serialize};
578
579 #[serde(crate = "serde_")]
580 #[derive(Serialize, Deserialize, PartialEq, Debug)]
581 struct Foo {
582 bar: String,
583 }
584
585 let value = Foo {
586 bar: "hello".into(),
587 };
588
589 let bencode = bendy::serde::to_bytes(&value)?;
590 assert_eq!(bencode, b"d3:bar5:helloe");
591
592 let deserialized = bendy::serde::from_bytes::<Foo>(&bencode)?;
593 assert_eq!(deserialized, value);
594
595 Ok(())
596
597 # }
598 ```
599
600 Information on how Rust types are represented in bencode is available in the
601 [serde module documentation](https://docs.rs/bendy/*/bendy/serde/index.html).
602
603 ### Reflection
604
605 Bendy supports rudimentary reflection for use in testing, fuzzing, and debugging.
606
607 > [!WARNING]
608 > This feature SHOULD NOT be used in production code.
609 > It is not as thoroughly tested as other parts of bendy.
610
611 To enable the feature only in your tests, you can depend on bendy like so:
612
613 ```toml
614 [dependencies.bendy]
615 version = "^0.4"
616
617 [dev-dependencies.bendy]
618 version = "^0.4"
619 features = ["inspect"]
620 ```
621
622 The API has been designed for convenience. It is intended to be used to construct evil data to ensure your program responds appropriately to it. One way of doing so is:
623
624 1) Build a valid serializable object that your program should be able to handle.
625 1) Encode the object to bencode.
626 1) Ingest the resulting bytes with the `inspect::inspect` method.
627 1) Use the returned `Inspectable` to make modifications that break your program's invariants.
628 1) Call `.emit()` on the `Inspectable` to receive a `Vec` of bytes which represents your modified object.
629 1) Attempt to deserialize the object and ensure deserialization fails if it should.
630 1) Attempt to use the deserialized object and ensure your program fails in the way it ought to.
631
632 One can also use the constructor methods of `Inspectable` to manually build objects, for example
633 when fuzzing.
634
635 The core of the API is the `Inspectable` enum, which represents the core primitives of bencode:
636 numbers, bytestrings, dicts and lists. The latter two may contain other `Inspectables`,
637 so this forms a rough AST-like data structure. There is also an enum variant
638 `Inspectable::Raw` which can be used to inject arbitrary bytes into a structure.
639
640 Inspectables have methods for traversal of the AST, rudimentary search, and mutation of nodes.
641 Most methods will panic instead of returning `Results` or `Options`, since any broken assumption
642 should result in a test failure.
643
644 Here is an example of making some modifications to an AST.
645
646 ```rust
647 # #[cfg(not(feature = "inspect"))]
648 # fn main() {}
649 # #[cfg(feature = "inspect")]
650 # fn main() {
651 use bendy::inspect::*;
652
653 // {
654 // aaa: 10,
655 // bbb: "hello",
656 // other: [
657 // {secret: "password"},
658 // ],
659 // }
660 let bytes = b"\
661 d\
662 3:aaa\
663 i10e\
664 3:bbb\
665 5:hello\
666 5:other\
667 l\
668 d\
669 6:secret\
670 8:password\
671 e\
672 e\
673 e\
674 ";
675
676 let mut i = inspect(bytes);
677
678 println!("Pretty printed repr:\n{}", i.as_rust_string_literal());
679
680 // Access list items or dict entries with `nth`
681 i.dict().nth(0).value
682 .replace(Inspectable::new_raw(b"invalid"));
683
684 // Dict entries can also be accessed with the `entry` method
685 i.dict().entry(b"bbb").value
686 .set_content_byterange(0..2, b'X');
687
688 // A Path object can be used to represent traversals.
689 // This is often more convenient, and enables re-use.
690
691 // Above, the `.dict()` call is used to coerce from
692 // `&mut Inspectable` to `&mut InDict`. When traversing
693 // deep structures, this can get quite verbose. This is
694 // not needed when using Paths for traversal.
695
696 // Paths can also be used to search the AST. Searches
697 // can only find one occurrence of an item. The first
698 // occurrence in the serialized representation will be
699 // found (depth first search in the AST).
700
701 i.find(&inspect_path().search_entry(b"secret").value())
702 .clear_content();
703
704 // Or without search:
705 i.find(&inspect_path().entry(b"other").value().nth(0).nth(0).value())
706 .clear_content();
707
708 assert_eq!(
709 i.emit().as_slice(),
710 b"d3:aaainvalid3:bbb5:XXllo5:otherld6:secret0:eee"
711 );
712 # }
713 ```
714
715 See the inspect module in the [docs](https://docs.rs/bendy/latest/bendy/) for the full API.
716
717 ## Usage of unsafe code
718 The parser would not require any unsafe code to work but it still contains a single unsafe call
719 to `str::from_utf8_unchecked`. This call is used to avoid a duplicated UTF-8 check when the
720 parser converts the bytes representing an incoming integer into a `&str` after its successful
721 validation.
722
723 Known unsafe usage from dependencies as of 2025-08-14:
724 * serde and serde_bytes: Eight usages. Only a risk if the `serde` feature is enabled.
725 * smallvec: Three usages. Only a risk if the `inspect` feature is enabled.
726
727 *Disclaimer: Further unsafe code may be introduced through the dependency on the `thiserror` and `rustversion` crates. As of 2025-08-14 these contain no unsafe code.*
728
729 ## Contributing
730
731 We welcome everyone to ask questions, open issues or provide merge requests.
732 Each merge request will be reviewed and either landed in the main tree or given
733 feedback for changes that would be required.
734
735 All code in this repository is under the [BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause)
736 license.