eva_common/
tools.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::Error;
use serde::{Deserialize, Deserializer, Serializer};
use std::str::FromStr;
use std::sync::atomic;
use std::sync::Arc;
use std::time::Duration;

#[inline]
pub fn get_eva_dir() -> String {
    std::env::var("EVA_DIR").unwrap_or_else(|_| "/opt/eva4".to_owned())
}

#[inline]
pub fn atomic_true() -> atomic::AtomicBool {
    atomic::AtomicBool::new(true)
}

#[inline]
pub fn arc_atomic_true() -> Arc<atomic::AtomicBool> {
    Arc::new(atomic::AtomicBool::new(true))
}

#[derive(Debug)]
pub enum SocketPath {
    Tcp(String),
    Udp(String),
    Unix(String),
}

impl FromStr for SocketPath {
    type Err = Error;

    /// # Panics
    ///
    /// Will panic on internal errors
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(if s.starts_with("tcp://") {
            SocketPath::Tcp(s.strip_prefix("tcp://").unwrap().to_owned())
        } else if s.starts_with("udp://") {
            SocketPath::Udp(s.strip_prefix("udp://").unwrap().to_owned())
        } else {
            SocketPath::Unix(s.to_owned())
        })
    }
}

/// # Panics
///
/// Will panic of neither path nor default specified
pub fn format_path(base: &str, path: Option<&str>, default: Option<&str>) -> String {
    if let Some(p) = path {
        if p.starts_with('/') {
            p.to_owned()
        } else {
            format!("{}/{}", base, p)
        }
    } else if let Some(d) = default {
        format!("{}/{}", base, d)
    } else {
        panic!("unable to format, neither path nor default specified");
    }
}

#[macro_export]
macro_rules! err_logger {
    () => {
        pub trait ErrLogger {
            /// log error and forget the result
            fn log_ef(self);
            /// log error as debug and forget the result
            fn log_efd(self);
            /// log error and keep the result
            fn log_err(self) -> Self;
            /// log error as debug and keep the result
            fn log_ed(self) -> Self;
            /// log error and forget the result with message
            fn log_ef_with(self, msg: impl ::std::fmt::Display);
            /// log error as debug and forget the result with message
            fn log_efd_with(self, msg: impl ::std::fmt::Display);
            /// log error and keep the result with message
            fn log_err_with(self, msg: impl ::std::fmt::Display) -> Self;
            /// log error as debug and keep the result with message
            fn log_ed_with(self, msg: impl ::std::fmt::Display) -> Self;
        }

        impl<R, E> ErrLogger for Result<R, E>
        where
            E: ::std::fmt::Display,
        {
            #[inline]
            fn log_ef(self) {
                if let Err(ref e) = self {
                    ::log::error!("{}", e);
                }
            }
            #[inline]
            fn log_efd(self) {
                if let Err(ref e) = self {
                    ::log::debug!("{}", e);
                }
            }
            #[inline]
            fn log_err(self) -> Self {
                if let Err(ref e) = self {
                    ::log::error!("{}", e);
                }
                self
            }
            #[inline]
            fn log_ed(self) -> Self {
                if let Err(ref e) = self {
                    ::log::debug!("{}", e);
                }
                self
            }
            #[inline]
            fn log_ef_with(self, msg: impl ::std::fmt::Display) {
                if let Err(ref e) = self {
                    ::log::error!("{}: {}", msg, e);
                }
            }
            #[inline]
            fn log_efd_with(self, msg: impl ::std::fmt::Display) {
                if let Err(ref e) = self {
                    ::log::debug!("{}: {}", msg, e);
                }
            }
            #[inline]
            fn log_err_with(self, msg: impl ::std::fmt::Display) -> Self {
                if let Err(ref e) = self {
                    ::log::error!("{}: {}", msg, e);
                }
                self
            }
            #[inline]
            fn log_ed_with(self, msg: impl ::std::fmt::Display) -> Self {
                if let Err(ref e) = self {
                    ::log::debug!("{}: {}", msg, e);
                }
                self
            }
        }
    };
}

// atomic functions (not implemented in serde for certain archs)
pub fn serialize_atomic_bool<S>(
    value: &atomic::AtomicBool,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_bool(value.load(atomic::Ordering::SeqCst))
}

pub fn deserialize_atomic_bool<'de, D>(deserializer: D) -> Result<atomic::AtomicBool, D::Error>
where
    D: Deserializer<'de>,
{
    let val = bool::deserialize(deserializer)?;
    Ok(atomic::AtomicBool::new(val))
}

pub fn deserialize_arc_atomic_bool<'de, D>(
    deserializer: D,
) -> Result<Arc<atomic::AtomicBool>, D::Error>
where
    D: Deserializer<'de>,
{
    let val = bool::deserialize(deserializer)?;
    Ok(Arc::new(atomic::AtomicBool::new(val)))
}

pub fn serialize_atomic_u64<S>(value: &atomic::AtomicU64, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_u64(value.load(atomic::Ordering::SeqCst))
}

pub fn deserialize_atomic_u64<'de, D>(deserializer: D) -> Result<atomic::AtomicU64, D::Error>
where
    D: Deserializer<'de>,
{
    let val = u64::deserialize(deserializer)?;
    Ok(atomic::AtomicU64::new(val))
}

pub fn deserialize_arc_atomic_u64<'de, D>(
    deserializer: D,
) -> Result<Arc<atomic::AtomicU64>, D::Error>
where
    D: Deserializer<'de>,
{
    let val = u64::deserialize(deserializer)?;
    Ok(Arc::new(atomic::AtomicU64::new(val)))
}

pub fn serialize_duration_as_f64<S>(t: &Duration, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_f64(t.as_secs_f64())
}

pub fn serialize_duration_as_u64<S>(t: &Duration, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_u64(t.as_secs())
}

#[allow(clippy::cast_possible_truncation)]
pub fn serialize_duration_as_micros<S>(t: &Duration, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_u64(t.as_micros() as u64)
}

#[allow(clippy::cast_possible_truncation)]
pub fn serialize_opt_duration_as_micros<S>(t: &Option<Duration>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(ref dur) = t {
        s.serialize_u64(dur.as_micros() as u64)
    } else {
        s.serialize_none()
    }
}

#[allow(clippy::cast_possible_truncation)]
pub fn serialize_duration_as_nanos<S>(t: &Duration, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_u64(t.as_nanos() as u64)
}

#[allow(clippy::cast_possible_truncation)]
pub fn serialize_opt_duration_as_nanos<S>(t: &Option<Duration>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(ref dur) = t {
        s.serialize_u64(dur.as_nanos() as u64)
    } else {
        s.serialize_none()
    }
}

pub fn serialize_opt_duration_as_f64<S>(t: &Option<Duration>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(ref dur) = t {
        s.serialize_f64(dur.as_secs_f64())
    } else {
        s.serialize_none()
    }
}

pub fn deserialize_duration_from_micros<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Duration::from_micros(u64::deserialize(deserializer)?))
}

pub fn deserialize_duration_from_nanos<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Duration::from_nanos(u64::deserialize(deserializer)?))
}

pub fn de_float_as_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Duration::from_secs_f64(f64::deserialize(deserializer)?))
}

pub fn de_opt_float_as_duration<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
    D: Deserializer<'de>,
{
    let t: Option<f64> = Option::deserialize(deserializer)?;
    Ok(t.map(Duration::from_secs_f64))
}

#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
pub fn de_float_as_duration_us<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Duration::from_nanos(
        (f64::deserialize(deserializer)? * 1000.0) as u64,
    ))
}

#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
pub fn de_opt_float_as_duration_us<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
    D: Deserializer<'de>,
{
    let t: Option<f64> = Option::deserialize(deserializer)?;
    Ok(t.map(|v| Duration::from_nanos((v * 1000.0) as u64)))
}

#[inline]
pub fn default_true() -> bool {
    true
}