1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::char::from_digit;
use std::convert::{TryFrom, TryInto};
use std::iter::once;
pub fn encode_property<T: Ord, Encoded: TryFrom<usize>>(
data: &[T],
property_mapping: &dyn Fn(&T) -> u8,
base: u8,
) -> Result<Encoded, Encoded::Error> {
let n = data.len();
let bits_string = data
.iter()
.take(n - 1)
.map(property_mapping)
.map(|digit| from_digit(digit as u32, base as u32).unwrap())
.collect::<String>();
usize::from_str_radix(&bits_string, base as u32)
.expect("The orientation1 should be convertible to the correct radix")
.try_into()
}
pub fn decode_property<ToDecode: TryInto<usize>>(
property: ToDecode,
base: u8,
) -> Result<Vec<u8>, ToDecode::Error> {
let property = property.try_into()?;
let bits_string = format!("{}", radix_fmt::radix(property, base));
let last_digit = base
- bits_string
.chars()
.map(|c| c.to_digit(base as u32).unwrap() as u8)
.sum::<u8>()
% base;
Ok(bits_string
.chars()
.map(|c| c.to_digit(base as u32).unwrap() as u8)
.chain(once(last_digit))
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
const SEQ: [u8; 8] = [3, 6, 5, 7, 0, 2, 1, 4];
const PROP: [u8; 8] = [2, 0, 0, 1, 1, 0, 0, 2];
fn mapping(x: &u8) -> u8 {
match *x {
3 | 4 => 2,
7 | 0 => 1,
6 | 5 | 2 | 1 => 0,
_ => panic!("should only be called with values from seq"),
}
}
#[test]
fn test_encode_property() {
assert_eq!(Ok(1494), encode_property(&SEQ, &mapping, 3));
}
#[test]
fn test_encode_property_fails_with_too_small_type() {
assert!(encode_property::<_, u8>(&SEQ, &mapping, 3).is_err());
}
#[test]
fn test_decode_property() {
assert_eq!(Ok(PROP.to_vec()), decode_property(1494, 3));
}
}