SHARE
TWEET

Untitled

a guest Apr 24th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct RunLength<I>
  2. where
  3.     I: Iterator,
  4. {
  5.     iter: I,
  6.     saved: Option<I::Item>,
  7. }
  8.  
  9. impl<I> RunLength<I>
  10. where
  11.     I: Iterator,
  12. {
  13.     fn new(iter: I) -> Self {
  14.         Self { iter, saved: None }
  15.     }
  16. }
  17.  
  18. impl<I> Iterator for RunLength<I>
  19. where
  20.     I: Iterator,
  21.     <I as std::iter::Iterator>::Item: PartialEq,
  22. {
  23.     type Item = (I::Item, usize);
  24.  
  25.     fn next(&mut self) -> Option<Self::Item> {
  26.         let c = self.saved.take().or_else(|| self.iter.next())?;
  27.  
  28.         let mut count = 1;
  29.         while let Some(n) = self.iter.next() {
  30.             if n == c {
  31.                 count += 1
  32.             } else {
  33.                 self.saved = Some(n);
  34.                 break;
  35.             }
  36.         }
  37.  
  38.         Some((c, count))
  39.     }
  40. }
  41.  
  42. pub fn encode_tiny(data: &str) -> String {
  43.     use std::fmt::Write;
  44.  
  45.     RunLength::new(data.chars()).fold(String::new(), |mut s, (c, count)| {
  46.         match count {
  47.             1 => s.push(c),
  48.             n => write!(&mut s, "{}{}", n, c).unwrap(),
  49.         }
  50.         s
  51.     })
  52. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top