libhardcopy 1.0.0

Generalized library for hardcopy/softcopy command line utilities.
Documentation
/// The EFF Large Diceware wordlist was designed for generating memorable
/// passphrases by rolling dice. Its 7776 entries are carefully chosen common
/// English words. Here, the first 4096 entries (indices 0–4095, covering 12
/// bits of entropy per word) are used to encode arbitrary binary data as a
/// 12-bit-per-word stream.
///
/// References
/// * EFF Dice-Generated Passphrases: https://www.eff.org/dice
///
mod algo;

pub use crate::plugins::diceware::algo::DICEWARE_INSTRUCTIONS;
use crate::plugins::diceware::algo::{bytes_to_wordlist, max_word_len, wordlist_to_bytes};
use crate::plugins::{GenerationError, HardCopyGenerator, LibPlugin, SoftCopyGenerator};
use crate::{
    HardCopy, HardCopyInput, HardCopySection, HardCopySectionContent, SoftCopy, SoftCopyInput,
};

const WORDS_PER_LINE: usize = 6;

pub struct DicewarePlugin;

const PLUGIN_NAME: &str = "EFF Large Diceware";
const PLUGIN_DESCRIPTION: &str = "Wordlist generation using the EFF Large Diceware word list.";

impl LibPlugin for DicewarePlugin {
    fn name(&self) -> String {
        PLUGIN_NAME.to_string()
    }
    fn description(&self) -> String {
        PLUGIN_DESCRIPTION.to_string()
    }
    fn instructions(&self) -> String {
        DICEWARE_INSTRUCTIONS.to_string()
    }
}

impl HardCopyGenerator for DicewarePlugin {
    fn generate_hard_copy(&self, softinput: &SoftCopyInput) -> Result<HardCopy, GenerationError> {
        let words = bytes_to_wordlist(softinput.to_bytes());
        let col_width = max_word_len();
        let lines: Vec<String> = words
            .chunks(WORDS_PER_LINE)
            .enumerate()
            .map(|(i, chunk)| {
                let padded: Vec<String> = chunk
                    .iter()
                    .map(|w| format!("{:width$}", w, width = col_width))
                    .collect();
                format!("{:04}: {}", i + 1, padded.join(" "))
            })
            .collect();
        let mut hardcopy = HardCopy::new();
        hardcopy.push(HardCopySection {
            name: PLUGIN_NAME.to_string(),
            content: HardCopySectionContent::Words(lines),
        });
        Ok(hardcopy)
    }
}

impl SoftCopyGenerator for DicewarePlugin {
    fn generate_soft_copy(&self, input: &mut HardCopyInput) -> Result<SoftCopy, GenerationError> {
        let word_refs: Vec<&str> = input.words().iter().map(String::as_str).collect();
        let bytes = wordlist_to_bytes(&word_refs);
        Ok(SoftCopy { bytes })
    }
}

#[cfg(test)]
mod test {
    use super::DICEWARE_INSTRUCTIONS;

    #[test]
    fn validate_instructions_non_empty() {
        assert!(
            !DICEWARE_INSTRUCTIONS.is_empty(),
            "Verify the instructions are not empty."
        );
    }
}