hyprshell_core_lib/util/
helpers.rs

1use std::fmt;
2use tracing::{debug, warn};
3
4pub trait GetFirstOrLast: Iterator + Sized {
5    fn get_first_or_last(self, last: bool) -> Option<Self::Item>;
6}
7impl<I: Iterator> GetFirstOrLast for I {
8    fn get_first_or_last(mut self, last: bool) -> Option<Self::Item> {
9        if last { self.last() } else { self.next() }
10    }
11}
12
13pub trait GetNextOrPrev: Iterator + Sized {
14    fn get_next_or_prev(self, last: bool, len: usize) -> Option<Self::Item>;
15}
16impl<I: Iterator> GetNextOrPrev for I {
17    fn get_next_or_prev(mut self, last: bool, len: usize) -> Option<Self::Item> {
18        if last {
19            if len == 0 {
20                None
21            } else {
22                // skip to the last element
23                self.nth(len - 1)
24            }
25        } else {
26            self.next()
27        }
28    }
29}
30
31pub trait RevIf<'a>: Iterator + Sized + 'a {
32    fn rev_if(self, cond: bool) -> Box<dyn Iterator<Item = Self::Item> + 'a>;
33}
34
35impl<'a, I: DoubleEndedIterator + 'a> RevIf<'a> for I {
36    fn rev_if(self, cond: bool) -> Box<dyn Iterator<Item = Self::Item> + 'a> {
37        if cond {
38            Box::new(self.rev())
39        } else {
40            Box::new(self)
41        }
42    }
43}
44
45pub trait WarnWithDetails<A> {
46    fn warn(self, msg: &str) -> Option<A>;
47}
48
49pub trait Warn<A> {
50    fn warn(self) -> Option<A>;
51}
52
53impl<A> WarnWithDetails<A> for Option<A> {
54    fn warn(self, msg: &str) -> Option<A> {
55        match self {
56            Some(o) => Some(o),
57            None => {
58                warn!("{}", msg);
59                None
60            }
61        }
62    }
63}
64
65impl<A, E: fmt::Debug + fmt::Display> WarnWithDetails<A> for Result<A, E> {
66    fn warn(self, msg: &str) -> Option<A> {
67        match self {
68            Ok(o) => Some(o),
69            Err(e) => {
70                warn!("{}: {}", msg, e);
71                debug!("{e:?}");
72                None
73            }
74        }
75    }
76}
77
78impl<A, E: fmt::Debug + fmt::Display> Warn<A> for Result<A, E> {
79    fn warn(self) -> Option<A> {
80        match self {
81            Ok(o) => Some(o),
82            Err(e) => {
83                warn!("{}", e);
84                debug!("{e:?}");
85                None
86            }
87        }
88    }
89}