Skip to main content

to_vec_with_shape

Function to_vec_with_shape 

Source
pub fn to_vec_with_shape<T>(
    value: &T,
    target_shape: &'static Shape,
) -> Result<Vec<u8>, SerializeError>
where T: Facet<'static>,
Expand description

Serializes a dynamic value (like facet_value::Value) to postcard bytes using a target shape to guide the serialization.

This is the inverse of from_slice_with_shape. It allows you to serialize a Value as if it were a typed value matching the target shape, without the Value type discriminants.

This is useful for scenarios where you need to:

  1. Parse JSON/YAML into a Value
  2. Serialize it to postcard bytes matching a specific typed schema

§Example

use facet::Facet;
use facet_value::Value;
use facet_postcard::{to_vec_with_shape, from_slice_with_shape};

#[derive(Debug, Facet, PartialEq)]
struct Point { x: i32, y: i32 }

// Parse JSON into a Value
let value: Value = facet_json::from_str(r#"{"x": 10, "y": 20}"#).unwrap();

// Serialize using Point's shape - produces postcard bytes for Point, not Value
let bytes = to_vec_with_shape(&value, Point::SHAPE).unwrap();

// Deserialize back into a typed Point
let point: Point = facet_postcard::from_slice(&bytes).unwrap();
assert_eq!(point, Point { x: 10, y: 20 });

§Arguments

  • value - A reference to a dynamic value type (like facet_value::Value)
  • target_shape - The shape describing the expected wire format

§Errors

Returns an error if:

  • The value is not a dynamic value type
  • The value’s structure doesn’t match the target shape