vortex_array/
metadata.rs

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