Skip to main content

lychee_lib/types/
hints.rs

1//! Provide the means to display practical user-friendly messages,
2//! which are collected during runtime.
3
4use std::{
5    collections::{BTreeSet, btree_set::IntoIter},
6    fmt::Display,
7    sync::Mutex,
8};
9
10/// Hints are accumulated during the whole program invocation.
11static HINTS: Mutex<BTreeSet<Hint>> = Mutex::new(BTreeSet::new());
12
13/// An informative and friendly message created during the invocation of the program
14/// to be displayed before termination, to improve user experience.
15#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
16pub struct Hint(String);
17
18impl Display for Hint {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(f, "{}", self.0)
21    }
22}
23
24impl From<String> for Hint {
25    fn from(value: String) -> Self {
26        Self(value)
27    }
28}
29
30impl From<&str> for Hint {
31    fn from(value: &str) -> Self {
32        Self(value.to_owned())
33    }
34}
35
36/// Collect a [`Hint`] to optionally be shown to users
37/// at a later point in time by using [`get_hints`].
38///
39///
40/// # Panics
41///
42/// Panics if the mutex is poisoned
43pub fn add_hint(hint: Hint) {
44    HINTS.lock().unwrap().insert(hint);
45}
46
47/// Format and collect a [`Hint`].
48/// Helper macro for [`add_hint`].
49#[macro_export]
50macro_rules! hint {
51    ($($arg:tt)*) => {{
52        $crate::add_hint(format!($($arg)*).into());
53    }};
54}
55
56/// Get [`Hint`]s to report to users
57///
58/// # Panics
59///
60/// Panics if the mutex is poisoned
61pub fn get_hints() -> IntoIter<Hint> {
62    HINTS.lock().unwrap().clone().into_iter()
63}