Skip to main content

vortex_array/
metadata.rs

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