# Is there an existing crate for conditional \`serde\` serialization or byte slices?

**URL:** <https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948>\
**Category:** help\
**Created:** [September 19, 2021, 5:36am UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948 "2021-09-19T05:36:31Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![fjarri](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/fjarri/32/16479_2.png) [@fjarri](https://users.rust-lang.org/u/fjarri)\
**Post date:** [September 19, 2021, 5:36am UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/1 "2021-09-19T05:36:31Z")

</div>

In several of my crates I found myself writing custom serializers/deserializers for byte-slice-like objects (something that can be easily represented as a byte slice and restored from one; e.g. byte slices themselves, `GenericArray<u8>` and so on) which would serialize to bytes if `is_human_readable()` is `false`, and to base64/hex otherwise. So, for example, in some custom struct I can say

```rust
#[derive(Serialize, Deserialize)]
pub struct MyStruct(
    #[serde(
        serialize_with = "serialize_bytes_as_hex",
        deserialize_with = "deserialize_bytes_as_hex"
    )]
    GenericArray<u8, U16>,
);

```

At this point it seems to be worth extracting to a separate crate, but I wonder if such a crate already exists, or perhaps `serde` itself has this functionality somehow built-in.

---

<div class="post-metadata">

**Author:** ![jhpratt](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jhpratt/32/37974_2.png) [@jhpratt](https://users.rust-lang.org/u/jhpratt)\
**Post date:** [September 19, 2021, 8:13am UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/2 "2021-09-19T08:13:24Z")

</div>

Keep in mind that the custom (de)serializer can call other implementations. You could do something like

```rust
impl Serialize for MyStruct {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<…, …> {
        if serializer.is_human_readable() {
            // human readable stuff here
            self.0.serialize(s)
        } else {
            // byte stuff here
        }
    }
}

```

(I don't know the actual API off-hand, but it's vaguely similar to this)

---

<div class="post-metadata">

**Author:** ![jonasbb](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jonasbb/32/3619_2.png) [@jonasbb](https://users.rust-lang.org/u/jonasbb)\
**Post date:** [September 19, 2021, 11:56am UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/3 "2021-09-19T11:56:32Z")

</div>

I am maintaining the [`serde_with` crate](https://github.com/jonasbb/serde_with) where I collect various of such helper functions. There are many such helper crate, since serde will not carry them.

In `serde_with` there is nothing yet which makes use of the `is_human_readable` flag. A single function like `serialize_bytes_as_hex` feels too restrictive for a general crate. The reason it is too restrictive, is that this is only one possible combination, but as you already wrote, base64, with all its variants, might also be interesting here, or maybe using `Display` which I have seen for IP addresses.

A more general version could look like `IfHumanReadable<Hex, Bytes>`, which would require that the field can be serialized using either `Hex` or `Bytes` and picks based on the `is_human_readable` flag. This design allows you to plug in the correct variants for both possibilities. If a shorter name is desired, it is always possible to add a type alias.

---

<div class="post-metadata">

**Author:** ![fjarri](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/fjarri/32/16479_2.png) [@fjarri](https://users.rust-lang.org/u/fjarri)\
**Post date:** [September 19, 2021, 9:37pm UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/4 "2021-09-19T21:37:22Z")

</div>

Thanks, I'll see if I can perhaps come up with some API that would fit `serde_with`. I am not sure I understand your `IfHumanReadable` proposition though - is it supposed to be a trait? And `Hex` and `Bytes` are types implementing `From<T>` (where `T` is our type) and `Serializable`? There may be problems with defining generic traits over foreign types.

---

<div class="post-metadata">

**Author:** ![jonasbb](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jonasbb/32/3619_2.png) [@jonasbb](https://users.rust-lang.org/u/jonasbb)\
**Post date:** [September 19, 2021, 11:23pm UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/5 "2021-09-19T23:23:08Z")

</div>

In `serde_with` I try to explore how you can compose custom serialization logic from smaller parts. It works with two traits `SerializeAs`/`DeserializeAs`, which are mostly like the serde equivalent ones, expect that they allow you to extend it with new types and to customize containers (think `Vec`, `HashMap`). The `IfHumanReadable` would be a zero sized struct with two generic parameters. It would implement

```rust
impl<T, IF, ELSE> SerializeAs<T> for IfHumanReadable<IF, ELSE>
where
    IF: SerializeAs<T>,
    ELSE: SerializeAs<T>,
{...}

```

`IfHumanReadable` would behave identical to `IF`, if the format is human readable, and identical to `ELSE` if not.  
`Hex` and `Bytes` are two other zero sized types implementing `SerializeAs`. I was mainly referring with their names to your original post, but two such types already exists in the crate.  
I hope this clarifies the situation a bit.

This "trick" of having a zero sized type with generic arguments is a nice way of passing (static) arguments to the serialization code, which also works with plain serde.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [December 18, 2021, 11:23pm UTC](https://users.rust-lang.org/t/is-there-an-existing-crate-for-conditional-serde-serialization-or-byte-slices/64948/6 "2021-12-18T23:23:39Z")

</div>

Closed on December 18, 2021, 11:23pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
