Conversation
|
||
## Encoding | ||
|
||
<!-- TODO --> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Although trit variables should contain only -1
, 0
or 1
they are however of type i8
and these restrictions are not forced by compiler. Invalid out of range trit values can also come from unchecked javascript code. So there are two solutions to the problem: 1. make encoding checked and fail if some trit is out of range, but it's rather slow, and 2. make encoding fail-safe by assigning some default value to invalid values of a trit (it'll be safe and reasonably fast).
A fail-safe and fast encoding can look like this:
LUT: [[[[[u8; 4]; 4]; 4]; 4]; 4];
fn encode_unchecked(t: &[i8; 5]) -> u8 {
let i0 = t[0] & 3; // take lower two bits
let i1 = t[1] & 3;
let i2 = t[2] & 3;
let i3 = t[3] & 3;
let i4 = t[4] & 3;
LUT[i0][i1][i2][i3][i4]
}
In this case we have the following correspondence between values of type i8
and trits:
0->0
, 1->+1
, 2->0
, 3->-1
, 4->0
, 5->+1
, 6->0
, 7->-1
, and so on.
In addition to a fast unchecked (but safe) function we can have a checked (but slower) function.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since this is implementation detail I think I'll post the raw LUTs with no modification to them but insist on the safety concerns by including what you just wrote.
|
||
# Rationale and alternatives | ||
|
||
<!-- TODO --> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What other operations should be supported for an encoding? If we consider [u8]
as array of trit quintuples we might want to copy some subrange of trits that is not aligned to a bound of 5 trits (for example, copy trits from 2 to 13 encoded as bytes):
fn copy(from: &[u8], from_offset: usize, to: &mut [u8], to_offset: usize, count: usize)
A trivial implementation would first decode from
into trits and then encode subrange of the trits into to
bytes. But it uses additional memory and two conversions (from and to bytes). A more efficient implementation would use no additional memory and one conversion via a more intricate LUT.
Rendered