wow_alchemy_utils/
debug.rs

1use std::{cmp, fmt, sync};
2
3#[cfg(feature = "trimmed-debug-output")]
4pub const FIRST_N_ELEMENTS: usize = 7;
5
6pub trait HasLength {
7    type Item: fmt::Debug;
8
9    fn len2(&self) -> usize;
10    fn get_first_n(&self, elements: usize) -> &[Self::Item];
11}
12
13impl<T: fmt::Debug> HasLength for &[T] {
14    type Item = T;
15    fn len2(&self) -> usize {
16        self.len()
17    }
18    fn get_first_n(&self, elements: usize) -> &[Self::Item] {
19        let end = cmp::min(elements, self.len());
20        &self[..end]
21    }
22}
23
24impl<T: fmt::Debug> HasLength for Vec<T> {
25    type Item = T;
26    fn len2(&self) -> usize {
27        self.len()
28    }
29    fn get_first_n(&self, elements: usize) -> &[Self::Item] {
30        let end = cmp::min(elements, self.len());
31        &self[..end]
32    }
33}
34
35impl<T: ?Sized + HasLength> HasLength for sync::Arc<T> {
36    type Item = T::Item;
37    fn len2(&self) -> usize {
38        self.as_ref().len2()
39    }
40    fn get_first_n(&self, elements: usize) -> &[Self::Item] {
41        self.as_ref().get_first_n(elements)
42    }
43}
44
45#[cfg(feature = "trimmed-debug-output")]
46pub fn trimmed_collection_fmt<T: HasLength + fmt::Debug>(
47    n: &T,
48    f: &mut fmt::Formatter,
49) -> fmt::Result {
50    let first_three = n.get_first_n(FIRST_N_ELEMENTS);
51    let num_elements = cmp::max(0, n.len2() - first_three.len());
52
53    if num_elements == 0 {
54        write!(f, "{:#?}", n)
55    } else {
56        write!(f, "{:#?} + {} elements", first_three, num_elements)
57    }
58}
59#[cfg(not(feature = "trimmed-debug-output"))]
60pub fn trimmed_collection_fmt<T: HasLength + fmt::Debug>(
61    n: &T,
62    f: &mut fmt::Formatter,
63) -> fmt::Result {
64    write!(f, "{:#?}", n)
65}
66
67#[cfg(feature = "trimmed-debug-output")]
68pub fn option_trimmed_collection_fmt<T: HasLength + fmt::Debug>(
69    n: &Option<T>,
70    f: &mut fmt::Formatter,
71) -> fmt::Result {
72    if let Some(val) = n.as_ref() {
73        let first_three = val.get_first_n(FIRST_N_ELEMENTS);
74        let num_elements = cmp::max(0, val.len2() - first_three.len());
75
76        if num_elements == 0 {
77            write!(f, "Some({:#?})", n)
78        } else {
79            write!(f, "Some({:#?} + {} elements)", first_three, num_elements)
80        }
81    } else {
82        write!(f, "{:#?}", n)
83    }
84}
85#[cfg(not(feature = "trimmed-debug-output"))]
86pub fn option_trimmed_collection_fmt<T: HasLength + fmt::Debug>(
87    n: &Option<T>,
88    f: &mut fmt::Formatter,
89) -> fmt::Result {
90    write!(f, "{:#?}", n)
91}