common_base/
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
15use serde::{Deserialize, Deserializer};
16
17/// Deserialize an empty string as the default value.
18pub fn empty_string_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
19where
20    D: Deserializer<'de>,
21    T: Default + Deserialize<'de>,
22{
23    let s = String::deserialize(deserializer)?;
24
25    if s.is_empty() {
26        Ok(T::default())
27    } else {
28        T::deserialize(serde::de::value::StringDeserializer::<D::Error>::new(s))
29            .map_err(serde::de::Error::custom)
30    }
31}