Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. macro_rules! reassign {
  2. // Init: manually feed incrementing indices
  3. (
  4. ( $($tt:tt)* ) = $expr:expr
  5. ) => (
  6. let temp = $expr;
  7. reassign! {
  8. @indices [0 1 2 3 4 5 6 7 8 9 10 11 12]
  9. ( $($tt)* ) = temp
  10. }
  11. );
  12.  
  13. // Handling left-hand-side step-by-step
  14. // New binding case
  15. (@indices
  16. [ $cur_index:tt $($rest_indices:tt)* ]
  17. (
  18. let $var:pat
  19. $(
  20. , $($rest:tt)*
  21. )?
  22. ) = $expr:ident
  23. ) => (
  24. let $var = $expr.$cur_index;
  25. reassign! {
  26. @indices [ $($rest_indices)* ]
  27. (
  28. $( $($rest)* )?
  29. ) = $expr
  30. }
  31. );
  32.  
  33. // Nested tuple case
  34. (@indices
  35. [ $cur_index:tt $($rest_indices:tt)* ]
  36. (
  37. ( $($tt:tt)* )
  38. $(
  39. , $($rest:tt)*
  40. )?
  41. ) = $expr:ident
  42. ) => (
  43. reassign!( ($($tt)*) = $expr.$cur_index );
  44. reassign! {
  45. @indices [ $($rest_indices)* ]
  46. (
  47. $( $($rest)* )?
  48. ) = $expr
  49. }
  50. );
  51.  
  52. // place expression case (`*(&mut ...)` or varname)
  53. (@indices
  54. [ $cur_index:tt $($rest_indices:tt)* ]
  55. (
  56. $var:expr
  57. $(
  58. , $($rest:tt)*
  59. )?
  60. ) = $expr:ident
  61. ) => (
  62. $var = $expr.$cur_index;
  63. reassign! {
  64. @indices [ $($rest_indices)* ]
  65. (
  66. $( $($rest)* )?
  67. ) = $expr
  68. }
  69. );
  70.  
  71. // Termination
  72. (@indices
  73. $indices:tt
  74. () = $expr:ident
  75. ) => ();
  76.  
  77. // Bad termination: exhausted indices
  78. (@indices
  79. []
  80. $vars:tt = $expr:ident
  81. ) => (
  82. compile_error! {
  83. "`reassign!` only supports up to 12-tuples"
  84. }
  85. );
  86. }
  87.  
  88. fn main ()
  89. {
  90. let mut a = [0, 0];
  91. reassign! {
  92. (
  93. (a[0],), a[1], let z,
  94. ) = (
  95. (42,), 27, 0,
  96. )
  97. }
  98. dbg!(a.iter().sum::<i32>());
  99. dbg!(z);
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement