vortex_array/
metadata.rs

1use std::fmt::{Debug, Formatter};
2use std::ops::Deref;
3
4use vortex_error::{VortexResult, vortex_bail};
5
6/// Trait for serializing Vortex metadata to a vector of unaligned bytes.
7pub trait SerializeMetadata {
8    fn serialize(self) -> Vec<u8>;
9}
10
11/// Trait for deserializing Vortex metadata from a vector of unaligned bytes.
12pub trait DeserializeMetadata
13where
14    Self: Sized,
15{
16    /// The fully deserialized type of the metadata.
17    type Output;
18
19    /// Deserialize metadata from a vector of unaligned bytes.
20    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output>;
21}
22
23/// Empty array metadata
24#[derive(Debug)]
25pub struct EmptyMetadata;
26
27impl SerializeMetadata for EmptyMetadata {
28    fn serialize(self) -> Vec<u8> {
29        vec![]
30    }
31}
32
33impl DeserializeMetadata for EmptyMetadata {
34    type Output = EmptyMetadata;
35
36    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output> {
37        if !metadata.is_empty() {
38            vortex_bail!("EmptyMetadata should not have metadata bytes")
39        }
40        Ok(EmptyMetadata)
41    }
42}
43
44/// A utility wrapper for raw metadata serialization. This delegates the serialiation step
45/// to the arrays' vtable.
46pub struct RawMetadata(pub Vec<u8>);
47
48impl SerializeMetadata for RawMetadata {
49    fn serialize(self) -> Vec<u8> {
50        self.0
51    }
52}
53
54impl DeserializeMetadata for RawMetadata {
55    type Output = Vec<u8>;
56
57    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output> {
58        Ok(metadata.to_vec())
59    }
60}
61
62impl Debug for RawMetadata {
63    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
64        write!(f, "\"{}\"", self.0.escape_ascii())
65    }
66}
67
68/// A utility wrapper for Prost metadata serialization.
69pub struct ProstMetadata<M>(pub M);
70
71impl<M> Deref for ProstMetadata<M> {
72    type Target = M;
73
74    fn deref(&self) -> &Self::Target {
75        &self.0
76    }
77}
78
79impl<M: Debug> Debug for ProstMetadata<M> {
80    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
81        self.0.fmt(f)
82    }
83}
84
85impl<M> SerializeMetadata for ProstMetadata<M>
86where
87    M: prost::Message,
88{
89    fn serialize(self) -> Vec<u8> {
90        self.0.encode_to_vec()
91    }
92}
93
94impl<M> DeserializeMetadata for ProstMetadata<M>
95where
96    M: Debug,
97    M: prost::Message + Default,
98{
99    type Output = M;
100
101    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output> {
102        Ok(M::decode(metadata)?)
103    }
104}