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
use serde::Serialize;
use tracing::Level;
#[derive(Debug)]
pub struct RpcTracing(tracing::Span);
impl RpcTracing {
pub fn method_call(method: &str) -> Self {
Self(tracing::span!(tracing::Level::DEBUG, "method_call", %method))
}
pub fn notification(method: &str) -> Self {
Self(tracing::span!(tracing::Level::DEBUG, "notification", %method))
}
pub fn batch() -> Self {
Self(tracing::span!(tracing::Level::DEBUG, "batch"))
}
pub fn into_span(self) -> tracing::Span {
self.0
}
}
pub fn tx_log_from_str(s: impl AsRef<str>, max: u32) {
if tracing::enabled!(Level::TRACE) {
let msg = truncate_at_char_boundary(s.as_ref(), max as usize);
tracing::trace!(send = msg);
}
}
pub fn tx_log_from_json(s: &impl Serialize, max: u32) {
if tracing::enabled!(Level::TRACE) {
let json = serde_json::to_string(s).unwrap_or_default();
let msg = truncate_at_char_boundary(&json, max as usize);
tracing::trace!(send = msg);
}
}
pub fn rx_log_from_str(s: impl AsRef<str>, max: u32) {
if tracing::enabled!(Level::TRACE) {
let msg = truncate_at_char_boundary(s.as_ref(), max as usize);
tracing::trace!(recv = msg);
}
}
pub fn rx_log_from_json(s: &impl Serialize, max: u32) {
if tracing::enabled!(Level::TRACE) {
let res = serde_json::to_string(s).unwrap_or_default();
let msg = truncate_at_char_boundary(res.as_str(), max as usize);
tracing::trace!(recv = msg);
}
}
pub fn rx_log_from_bytes(bytes: &[u8], max: u32) {
if tracing::enabled!(Level::TRACE) {
let res = serde_json::from_slice::<serde_json::Value>(bytes).unwrap_or_default();
rx_log_from_json(&res, max);
}
}
fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
if s.len() < max {
return s;
}
match s.char_indices().nth(max as usize) {
None => s,
Some((idx, _)) => &s[..idx],
}
}
#[cfg(test)]
mod tests {
use super::truncate_at_char_boundary;
#[test]
fn truncate_at_char_boundary_works() {
assert_eq!(truncate_at_char_boundary("ボルテックス", 0), "");
assert_eq!(truncate_at_char_boundary("ボルテックス", 4), "ボルテッ");
assert_eq!(truncate_at_char_boundary("ボルテックス", 100), "ボルテックス");
assert_eq!(truncate_at_char_boundary("hola-hola", 4), "hola");
}
}