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)]
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
49/// A utility wrapper for raw metadata serialization. This delegates the serialiation step
50/// to the arrays' vtable.
51pub struct RawMetadata(pub Vec<u8>);
52
53impl SerializeMetadata for RawMetadata {
54    fn serialize(self) -> Vec<u8> {
55        self.0
56    }
57}
58
59impl DeserializeMetadata for RawMetadata {
60    type Output = Vec<u8>;
61
62    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output> {
63        Ok(metadata.to_vec())
64    }
65}
66
67impl Debug for RawMetadata {
68    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69        write!(f, "\"{}\"", self.0.escape_ascii())
70    }
71}
72
73/// A utility wrapper for Prost metadata serialization.
74pub struct ProstMetadata<M>(pub M);
75
76impl<M> Deref for ProstMetadata<M> {
77    type Target = M;
78
79    #[inline]
80    fn deref(&self) -> &Self::Target {
81        &self.0
82    }
83}
84
85impl<M: Debug> Debug for ProstMetadata<M> {
86    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
87        self.0.fmt(f)
88    }
89}
90
91impl<M> SerializeMetadata for ProstMetadata<M>
92where
93    M: prost::Message,
94{
95    fn serialize(self) -> Vec<u8> {
96        self.0.encode_to_vec()
97    }
98}
99
100impl<M> DeserializeMetadata for ProstMetadata<M>
101where
102    M: Debug,
103    M: prost::Message + Default,
104{
105    type Output = M;
106
107    fn deserialize(metadata: &[u8]) -> VortexResult<Self::Output> {
108        Ok(M::decode(metadata)?)
109    }
110}