C-style switch statement with fall-through in Rust
Asked Answered
E

0

8

The match in Rust only executes one arm. I found this code snippet from Murmurhash 3:

switch(len & 15)
{
  case 15: k2 ^= ((uint64_t)tail[14]) << 48;
  case 14: k2 ^= ((uint64_t)tail[13]) << 40;
  case 13: k2 ^= ((uint64_t)tail[12]) << 32;
  case 12: k2 ^= ((uint64_t)tail[11]) << 24;
  case 11: k2 ^= ((uint64_t)tail[10]) << 16;
  case 10: k2 ^= ((uint64_t)tail[ 9]) << 8;
  case  9: k2 ^= ((uint64_t)tail[ 8]) << 0;
           k2 *= c2; k2  = ROTL64(k2,33); k2 *= c1; h2 ^= k2;

  case  8: k1 ^= ((uint64_t)tail[ 7]) << 56;
  case  7: k1 ^= ((uint64_t)tail[ 6]) << 48;
  case  6: k1 ^= ((uint64_t)tail[ 5]) << 40;
  case  5: k1 ^= ((uint64_t)tail[ 4]) << 32;
  case  4: k1 ^= ((uint64_t)tail[ 3]) << 24;
  case  3: k1 ^= ((uint64_t)tail[ 2]) << 16;
  case  2: k1 ^= ((uint64_t)tail[ 1]) << 8;
  case  1: k1 ^= ((uint64_t)tail[ 0]) << 0;
           k1 *= c1; k1  = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
};

This switch is the traditional C switch. Is it possible to write this in Rust in an elegant way? I couldn't find a way to implement this with match.

Ean answered 28/6, 2019 at 6:35 Comment(6)
that's called fall-through. See Idiomatic match with fall-through in RustMirador
How does the marked duplicate provides an answer to this question ? A playground link please :)Proto
I don't think the duplicate actually answers the general case of this question.Kyphosis
I believe Matthieu's answer to the other question adequately answers this one. That is: fall-through is not supported, so you'll need a loop.Dextrose
If you would like to check how fall-through is implemented in Rust, check this repo github.com/yyklll/murmurhash3Ean
While the marked duplicate was initially related to fall-through, fall-through is not the primary subject and none of the answers propose solutions which can be generalized to this situation. For this reason, I feel this question has not been answered already and should be reopened.Analogy

© 2022 - 2024 — McMap. All rights reserved.