essential_types/solution/
encode.rs

1//! # Encoding
2//! Encoding for solution types.
3use crate::Word;
4
5use super::Mutation;
6
7#[cfg(test)]
8mod tests;
9
10/// Returns the size in words of the encoded mutation.
11///
12/// 2 words for the key length and value length,
13/// plus the length of the key and value data.
14pub fn encode_mutation_size(mutation: &Mutation) -> usize {
15    2 + mutation.key.len() + mutation.value.len()
16}
17
18/// Encodes a mutation into a sequence of words.
19///
20/// # Layout
21/// ```text
22/// +-----------------+-----------------+-----------------+-----------------+
23/// | key length      | key             | value length    | value           |
24/// +-----------------+-----------------+-----------------+-----------------+
25/// ```
26pub fn encode_mutation(mutation: &Mutation) -> impl Iterator<Item = Word> + use<'_> {
27    // Saturating cast
28    let key_len: Word = mutation.key.len().try_into().unwrap_or(Word::MAX);
29    // Saturating cast
30    let value_len: Word = mutation.value.len().try_into().unwrap_or(Word::MAX);
31    std::iter::once(key_len)
32        .chain(mutation.key.iter().copied())
33        .chain(std::iter::once(value_len))
34        .chain(mutation.value.iter().copied())
35}
36
37/// Encodes a slice of mutations into a sequence of words.
38///
39/// # Layout
40/// ```text
41/// +-----------------+-----------------+-----------------+-----------------+
42/// | num mutations   | mutation 1      | mutation 2      | ...             |
43/// +-----------------+-----------------+-----------------+-----------------+
44/// ```
45pub fn encode_mutations(mutations: &[Mutation]) -> impl Iterator<Item = Word> + use<'_> {
46    // Saturating cast
47    let len: Word = mutations.len().try_into().unwrap_or(Word::MAX);
48    std::iter::once(len).chain(mutations.iter().flat_map(encode_mutation))
49}