junobuild_shared/serializers.rs
1use ciborium::{from_reader, into_writer};
2use serde::{Deserialize, Serialize};
3use std::borrow::Cow;
4
5/// Serializes a given value into a byte array.
6///
7/// # Arguments
8/// * `value` - A reference to the value to serialize.
9///
10/// # Returns
11/// A `Cow<[u8]>` representing the serialized data.
12///
13/// # Panics
14/// Panics if serialization fails.
15pub fn serialize_to_bytes<T: Serialize>(value: &T) -> Cow<[u8]> {
16 let mut bytes = vec![];
17 into_writer(value, &mut bytes).expect("Failed to serialize to bytes");
18 Cow::Owned(bytes)
19}
20
21/// Deserializes a value from a byte array.
22///
23/// # Arguments
24/// * `bytes` - A `Cow<'_, [u8]>` representing the bytes to deserialize from.
25///
26/// # Returns
27/// The deserialized value of type `T`.
28///
29/// # Panics
30/// Panics if deserialization fails.
31pub fn deserialize_from_bytes<T: for<'a> Deserialize<'a>>(bytes: Cow<'_, [u8]>) -> T {
32 from_reader(&*bytes).expect("Failed to deserialize from bytes")
33}
34
35/// Provides a default deserialization value for boolean fields, defaulting to `true`.
36///
37/// This function is a workaround for handling default values when deserializing with Serde,
38/// particularly useful in scenarios where boolean fields need to default to `true` instead
39/// of the usual `false` when not explicitly provided in the input.
40///
41/// # Returns
42/// Returns `Some(true)`, indicating the default value to use.
43pub fn deserialize_default_as_true() -> Option<bool> {
44 // https://github.com/serde-rs/serde/issues/1030#issuecomment-522278006
45
46 Some(true)
47}