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
use serde::Serialize;
use tracing::Level;

/// Helper for writing trace logs from str.
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);
	}
}

/// Helper for writing trace logs from JSON.
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);
	}
}

/// Helper for writing trace logs from str.
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);
	}
}

/// Helper for writing trace logs from JSON.
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);
	}
}

/// Helper for writing trace logs from bytes.
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);
	}
}

/// Find the next char boundary to truncate at.
fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
	if s.len() < max {
		return s;
	}

	match s.char_indices().nth(max) {
		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");
	}
}