risingwave_common/session_config/
opt.rs

1// Copyright 2025 RisingWave Labs
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 std::fmt::Display;
16use std::ops::{Deref, DerefMut};
17use std::str::FromStr;
18
19use serde::{Deserialize, Serialize};
20
21/// A session config wrapper that represents unset (`None`) as empty string.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct OptionConfig<T>(pub Option<T>);
25
26impl<T: FromStr> FromStr for OptionConfig<T> {
27    type Err = T::Err;
28
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        if s.is_empty() {
31            Ok(Self(None))
32        } else {
33            Ok(Self(Some(s.parse()?)))
34        }
35    }
36}
37
38impl<T: Display> Display for OptionConfig<T> {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        if let Some(inner) = &self.0 {
41            inner.fmt(f)
42        } else {
43            write!(f, "")
44        }
45    }
46}
47
48impl<T> From<Option<T>> for OptionConfig<T> {
49    fn from(v: Option<T>) -> Self {
50        Self(v)
51    }
52}
53
54impl<T> From<OptionConfig<T>> for Option<T> {
55    fn from(v: OptionConfig<T>) -> Self {
56        v.0
57    }
58}
59
60impl<T> Deref for OptionConfig<T> {
61    type Target = Option<T>;
62
63    fn deref(&self) -> &Self::Target {
64        &self.0
65    }
66}
67
68impl<T> DerefMut for OptionConfig<T> {
69    fn deref_mut(&mut self) -> &mut Self::Target {
70        &mut self.0
71    }
72}