Skip to main content

common_query/request/
base64_serde.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Serde adapters for byte fields encoded as base64 strings in JSON.
16
17use base64::Engine;
18use base64::prelude::BASE64_STANDARD;
19
20fn encode(bytes: &[u8]) -> String {
21    BASE64_STANDARD.encode(bytes)
22}
23
24fn decode(encoded: &str) -> Result<Vec<u8>, base64::DecodeError> {
25    BASE64_STANDARD.decode(encoded)
26}
27
28pub(crate) mod bytes {
29    use serde::de::Error;
30    use serde::{Deserialize, Deserializer, Serializer};
31
32    pub fn serialize<S>(value: &[u8], serializer: S) -> Result<S::Ok, S::Error>
33    where
34        S: Serializer,
35    {
36        serializer.serialize_str(&super::encode(value))
37    }
38
39    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
40    where
41        D: Deserializer<'de>,
42    {
43        let encoded = String::deserialize(deserializer)?;
44        super::decode(&encoded).map_err(|err| {
45            D::Error::custom(format!("invalid base64 dynamic filter payload: {err}"))
46        })
47    }
48}
49
50pub(crate) mod bytes_vec {
51    use serde::de::Error;
52    use serde::{Deserialize, Deserializer, Serialize, Serializer};
53
54    pub fn serialize<S>(values: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error>
55    where
56        S: Serializer,
57    {
58        values
59            .iter()
60            .map(|bytes| super::encode(bytes))
61            .collect::<Vec<_>>()
62            .serialize(serializer)
63    }
64
65    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Vec<u8>>, D::Error>
66    where
67        D: Deserializer<'de>,
68    {
69        Vec::<String>::deserialize(deserializer)?
70            .into_iter()
71            .map(|encoded| {
72                super::decode(&encoded).map_err(|error| {
73                    D::Error::custom(format!("invalid base64 bytes vector item: {error}"))
74                })
75            })
76            .collect()
77    }
78}