| 1 |
/// Magically unpack up to 6 values from 10 bits. |
| 2 |
/// |
| 3 |
/// Background: |
| 4 |
/// |
| 5 |
/// Let's start with a simpler example of packing a list of numbers. |
| 6 |
/// Let's say you want to store 2 values a and b, which can each be 0, 1, or 2. |
| 7 |
/// You can store this as x = a * 3 + b. Then you can get out (a, b) by doing a |
| 8 |
/// division by 3 with remainder, because this has the form of n * 3 + (something less than 3) |
| 9 |
/// |
| 10 |
/// Similar, for four values, you can use: |
| 11 |
/// |
| 12 |
/// ```text |
| 13 |
/// x = a * 27 + b * 9 + c * 3 + d. |
| 14 |
/// ^^^^^^^^^^^^^^^^^ == x % 27 |
| 15 |
/// ^^^^^^^^^ == x % 9 |
| 16 |
/// ^ == x % 3 |
| 17 |
/// x == 27 * a + rem27 |
| 18 |
/// rem27 == 9 * b + rem9 |
| 19 |
/// rem9 == 3 * c + rem3 |
| 20 |
/// rem3 = d |
| 21 |
/// ``` |
| 22 |
/// |
| 23 |
/// Written differently: |
| 24 |
/// `x = d + 3 * (c + 3 * (b + (3 * a)))` |
| 25 |
/// |
| 26 |
/// So that was the case for when all digits have the same range (0..3 in this example). |
| 27 |
/// |
| 28 |
/// In this function we want to decode a permutation. In a permutation of n items, |
| 29 |
/// for the first digit we can choose one of n items, for the second digit we can |
| 30 |
/// choose one of the remaining n - 1 items, for the third one of the remaining n - 2 etc. |
| 31 |
/// |
| 32 |
/// We have the choice between 6 registers, so n = 6 in this function. |
| 33 |
/// Each digit is stored zero-based. So a is in 0..6, b is in 0..5, c in 0..4 etc. |
| 34 |
/// |
| 35 |
/// We encode as (a, b, c) as c + 4 * (b + 5 * a) |
| 36 |
/// [...] |
| 37 |
pub fn decode_permutation_6(count: u32, mut encoding: u32) -> std::result::Result<[u8; 6], ()> { |
| 38 |
if count > 6 { |
| 39 |
return Err(()); |
| 40 |
} |
| 41 |
|
| 42 |
let mut compressed_regindexes = [0; 6]; |
| 43 |
|
| 44 |
if count > 4 { |
| 45 |
compressed_regindexes[4] = encoding % 2; |
| 46 |
encoding /= 2; |
| 47 |
} |
| 48 |
if count > 3 { |
| 49 |
compressed_regindexes[3] = encoding % 3; |
| 50 |
encoding /= 3; |
| 51 |
} |
| 52 |
if count > 2 { |
| 53 |
compressed_regindexes[2] = encoding % 4; |
| 54 |
encoding /= 4; |
| 55 |
} |
| 56 |
if count > 1 { |
| 57 |
compressed_regindexes[1] = encoding % 5; |
| 58 |
encoding /= 5; |
| 59 |
} |
| 60 |
if count > 0 { |
| 61 |
compressed_regindexes[0] = encoding; |
| 62 |
} |
| 63 |
|
| 64 |
if compressed_regindexes[0] >= 6 { |
| 65 |
return Err(()); |
| 66 |
} |
| 67 |
|
| 68 |
let mut registers = [0; 6]; |
| 69 |
let mut used = [false; 6]; |
| 70 |
for i in 0..count { |
| 71 |
let compressed_regindex = compressed_regindexes[i as usize]; |
| 72 |
debug_assert!(compressed_regindex < 6 - i); |
| 73 |
let uncompressed_regindex = (0..6) |
| 74 |
.filter(|ri| !used[*ri]) |
| 75 |
.nth(compressed_regindex as usize) |
| 76 |
.unwrap(); |
| 77 |
used[uncompressed_regindex] = true; |
| 78 |
registers[i as usize] = (uncompressed_regindex + 1) as u8; |
| 79 |
} |
| 80 |
Ok(registers) |
| 81 |
} |