Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  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(mut iter: I) -> Self {
  14. let saved = iter.next();
  15. Self { iter, saved }
  16. }
  17. }
  18.  
  19. impl<I> Iterator for RunLength<I>
  20. where
  21. I: Iterator,
  22. I::Item: PartialEq,
  23. {
  24. type Item = (I::Item, usize);
  25.  
  26. #[inline]
  27. fn next(&mut self) -> Option<Self::Item> {
  28. let c = self.saved.take().or_else(|| self.iter.next())?;
  29.  
  30. let mut count = 1;
  31. while let Some(n) = self.iter.next() {
  32. if n == c {
  33. count += 1
  34. } else {
  35. self.saved = Some(n);
  36. break;
  37. }
  38. }
  39.  
  40. Some((c, count))
  41. }
  42.  
  43. #[inline]
  44. fn fold<B, F>(mut self, init: B, mut f: F) -> B
  45. where
  46. F: FnMut(B, Self::Item) -> B,
  47. {
  48. let mut c = match self.saved.take().or_else(|| self.iter.next()) {
  49. Some(c) => c,
  50. None => return init,
  51. };
  52.  
  53. let mut count = 1;
  54. let mut value = init;
  55.  
  56. for n in self.iter {
  57. if n == c {
  58. count += 1
  59. } else {
  60. value = f(value, (c, count));
  61. c = n;
  62. count = 1;
  63. }
  64. }
  65.  
  66. f(value, (c, count))
  67. }
  68. }
  69.  
  70. pub fn encode_tiny(data: &str) -> String {
  71. use std::fmt::Write;
  72.  
  73. RunLength::new(data.chars()).fold(String::new(), |mut s, (c, count)| {
  74. match count {
  75. 1 => s.push(c),
  76. n => write!(&mut s, "{}{}", n, c).unwrap(),
  77. }
  78. s
  79. })
  80. }
  81.  
  82. // encode (procedural) time: [18.343 ms 18.581 ms 18.838 ms]
  83. // Found 13 outliers among 100 measurements (13.00%)
  84. // 9 (9.00%) high mild
  85. // 4 (4.00%) high severe
  86. //
  87. // encode (tiny) time: [21.206 ms 21.486 ms 21.787 ms]
  88. // Found 5 outliers among 100 measurements (5.00%)
  89. // 5 (5.00%) high mild
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement