| 1 |
# serde\_bytes [](https://github.com/serde-rs/bytes/actions?query=branch%3Amaster) [](https://crates.io/crates/serde_bytes) |
| 2 |
|
| 3 |
Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`. |
| 4 |
|
| 5 |
```toml |
| 6 |
[dependencies] |
| 7 |
serde_bytes = "0.11" |
| 8 |
``` |
| 9 |
|
| 10 |
## Explanation |
| 11 |
|
| 12 |
Without specialization, Rust forces Serde to treat `&[u8]` just like any |
| 13 |
other slice and `Vec<u8>` just like any other vector. In reality this |
| 14 |
particular slice and vector can often be serialized and deserialized in a |
| 15 |
more efficient, compact representation in many formats. |
| 16 |
|
| 17 |
When working with such a format, you can opt into specialized handling of |
| 18 |
`&[u8]` by wrapping it in `serde_bytes::Bytes` and `Vec<u8>` by wrapping it |
| 19 |
in `serde_bytes::ByteBuf`. |
| 20 |
|
| 21 |
Additionally this crate supports the Serde `with` attribute to enable efficient |
| 22 |
handling of `&[u8]` and `Vec<u8>` in structs without needing a wrapper type. |
| 23 |
|
| 24 |
## Example |
| 25 |
|
| 26 |
```rust |
| 27 |
use serde::{Deserialize, Serialize}; |
| 28 |
|
| 29 |
#[derive(Deserialize, Serialize)] |
| 30 |
struct Efficient<'a> { |
| 31 |
#[serde(with = "serde_bytes")] |
| 32 |
bytes: &'a [u8], |
| 33 |
|
| 34 |
#[serde(with = "serde_bytes")] |
| 35 |
byte_buf: Vec<u8>, |
| 36 |
} |
| 37 |
``` |
| 38 |
|
| 39 |
<br> |
| 40 |
|
| 41 |
#### License |
| 42 |
|
| 43 |
<sup> |
| 44 |
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version |
| 45 |
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. |
| 46 |
</sup> |
| 47 |
|
| 48 |
<br> |
| 49 |
|
| 50 |
<sub> |
| 51 |
Unless you explicitly state otherwise, any contribution intentionally submitted |
| 52 |
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall |
| 53 |
be dual licensed as above, without any additional terms or conditions. |
| 54 |
</sub> |