daily pastebin goal
26%
SHARE
TWEET

Untitled

a guest Jan 18th, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. macro_rules! expand_patterns {
  2.     // if we're out of patterns, call `f` with the iterator we've constructed
  3.     (CONTINUE: ($iter:ident => $use_iter:ident)) => {
  4.         break $use_iter($iter);
  5.     };
  6.     (
  7.         // distinguishes this case from the entry case
  8.         CONTINUE:
  9.         // we have to define the identifier used for the iterator because of hygiene
  10.         // defining the identifier of the function is just for reusability
  11.         ($iter:ident => $use_iter:ident)
  12.         // expressions cannot be followed by blocks in macros
  13.         if let $pat:pat = ($expr:expr) $new_iter:block $($rest:tt)*
  14.     ) => {
  15.          if let $pat = $expr {
  16.             let $iter = $new_iter;
  17.             // we recurse with the remaining patterns in both cases
  18.              expand_patterns!(CONTINUE: ($iter => $use_iter) $($rest)*);
  19.          } else {
  20.              expand_patterns!(CONTINUE: ($iter => $use_iter) $($rest)*);
  21.          }
  22.     };
  23.     // entry case
  24.     (($iter:ident => $use_iter:ident) $($args:tt)*) => {
  25.         // we expand inside a loop so we can use `break` as flow control
  26.         loop {
  27.              expand_patterns!(CONTINUE: ($iter => $use_iter) $($args)*);
  28.         }
  29.     }
  30. }
  31.          
  32.          
  33. fn use_iter(iter: impl Iterator<Item = (u64, bool)>) {
  34.     for (t, v) in iter {
  35.         println!("{}: {:?}", t, v);
  36.     }
  37. }        
  38.  
  39. fn main() {
  40.     let start_time = Some(0);
  41.     let end_time = Some(100);
  42.     let photon_count = Some(100);
  43.    
  44.     let iter = (0 .. 100).map(|t| (t, t & 1 != 0));
  45.  
  46.     let res = expand_patterns! {
  47.         (iter => use_iter)
  48.         if let Some(start_time) = (start_time) {
  49.             iter.skip_while(|&(t, _)| t < start_time)
  50.         }
  51.        
  52.         if let Some(end_time) = (end_time) {
  53.             iter.take_while(|&(t, _)| t <= end_time)
  54.         }
  55.        
  56.         if let Some(photon_count) = (photon_count) {
  57.             iter.take(photon_count)
  58.         }
  59.     };
  60. }
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