lib.rs

  1#[cfg(any(test, feature = "test-support"))]
  2pub mod test;
  3
  4use futures::Future;
  5use std::{
  6    cmp::Ordering,
  7    ops::AddAssign,
  8    pin::Pin,
  9    task::{Context, Poll},
 10};
 11
 12pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 13    let prev = *value;
 14    *value += T::from(1);
 15    prev
 16}
 17
 18/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 19/// enforcing a maximum length. Sort the items according to the given callback. Before calling this,
 20/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 21pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 22where
 23    I: IntoIterator<Item = T>,
 24    F: FnMut(&T, &T) -> Ordering,
 25{
 26    let mut start_index = 0;
 27    for new_item in new_items {
 28        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 29            let index = start_index + i;
 30            if vec.len() < limit {
 31                vec.insert(index, new_item);
 32            } else if index < vec.len() {
 33                vec.pop();
 34                vec.insert(index, new_item);
 35            }
 36            start_index = index;
 37        }
 38    }
 39}
 40
 41pub trait ResultExt {
 42    type Ok;
 43
 44    fn log_err(self) -> Option<Self::Ok>;
 45    fn warn_on_err(self) -> Option<Self::Ok>;
 46}
 47
 48impl<T, E> ResultExt for Result<T, E>
 49where
 50    E: std::fmt::Debug,
 51{
 52    type Ok = T;
 53
 54    fn log_err(self) -> Option<T> {
 55        match self {
 56            Ok(value) => Some(value),
 57            Err(error) => {
 58                log::error!("{:?}", error);
 59                None
 60            }
 61        }
 62    }
 63
 64    fn warn_on_err(self) -> Option<T> {
 65        match self {
 66            Ok(value) => Some(value),
 67            Err(error) => {
 68                log::warn!("{:?}", error);
 69                None
 70            }
 71        }
 72    }
 73}
 74
 75pub trait TryFutureExt {
 76    fn log_err(self) -> LogErrorFuture<Self>
 77    where
 78        Self: Sized;
 79    fn warn_on_err(self) -> LogErrorFuture<Self>
 80    where
 81        Self: Sized;
 82}
 83
 84impl<F, T> TryFutureExt for F
 85where
 86    F: Future<Output = anyhow::Result<T>>,
 87{
 88    fn log_err(self) -> LogErrorFuture<Self>
 89    where
 90        Self: Sized,
 91    {
 92        LogErrorFuture(self, log::Level::Error)
 93    }
 94
 95    fn warn_on_err(self) -> LogErrorFuture<Self>
 96    where
 97        Self: Sized,
 98    {
 99        LogErrorFuture(self, log::Level::Warn)
100    }
101}
102
103pub struct LogErrorFuture<F>(F, log::Level);
104
105impl<F, T> Future for LogErrorFuture<F>
106where
107    F: Future<Output = anyhow::Result<T>>,
108{
109    type Output = Option<T>;
110
111    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
112        let level = self.1;
113        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
114        match inner.poll(cx) {
115            Poll::Ready(output) => Poll::Ready(match output {
116                Ok(output) => Some(output),
117                Err(error) => {
118                    log::log!(level, "{:?}", error);
119                    None
120                }
121            }),
122            Poll::Pending => Poll::Pending,
123        }
124    }
125}
126
127struct Defer<F: FnOnce()>(Option<F>);
128
129impl<F: FnOnce()> Drop for Defer<F> {
130    fn drop(&mut self) {
131        self.0.take().map(|f| f());
132    }
133}
134
135pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
136    Defer(Some(f))
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn test_extend_sorted() {
145        let mut vec = vec![];
146
147        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
148        assert_eq!(vec, &[21, 17, 13, 8, 1]);
149
150        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
151        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
152
153        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
154        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
155    }
156}