libhardcopy 1.0.1

Generalized library for hardcopy/softcopy command line utilities.
Documentation
use wordlists::EFF_LARGE_WORDLIST;

pub const DICEWARE_INSTRUCTIONS: &str =
    include_str!("../../../static/wordlists/diceware/instructions.txt");

/// Number of entries from EFF_LARGE_WORDLIST used for encoding (2^12 = 4096).
const ENCODING_SIZE: usize = 4096;

/// Returns the length of the longest word used for encoding.
pub(crate) fn max_word_len() -> usize {
    EFF_LARGE_WORDLIST[..ENCODING_SIZE]
        .iter()
        .map(|(_, w)| w.len())
        .max()
        .unwrap_or(0)
}

/// Encode `bytes` as EFF Large Diceware words using a 12-bit-per-word stream.
///
/// A 4-byte little-endian length prefix is prepended. Bits are packed MSB-first;
/// if the total bit count is not a multiple of 12, the final word is padded with
/// zero bits on the right. Only the first 4096 entries (indices 0–4095) of the
/// EFF Large wordlist are used.
pub(crate) fn bytes_to_wordlist(bytes: &[u8]) -> Vec<&'static str> {
    let len = bytes.len() as u32;
    let mut data = Vec::with_capacity(4 + bytes.len());
    data.extend_from_slice(&len.to_le_bytes());
    data.extend_from_slice(bytes);

    let mut words = Vec::new();
    let mut buf: u32 = 0;
    let mut buf_len: usize = 0;

    for byte in &data {
        buf = (buf << 8) | (*byte as u32);
        buf_len += 8;
        while buf_len >= 12 {
            buf_len -= 12;
            let index = ((buf >> buf_len) & 0xFFF) as usize;
            words.push(EFF_LARGE_WORDLIST[index].1);
        }
    }
    // Flush remaining bits, padding with zeros to fill the last 12-bit word.
    if buf_len > 0 {
        let index = ((buf << (12 - buf_len)) & 0xFFF) as usize;
        words.push(EFF_LARGE_WORDLIST[index].1);
    }

    words
}

/// Decode EFF Large Diceware words back to the original bytes, stripping the
/// 4-byte length prefix inserted by `bytes_to_wordlist`.
pub(crate) fn wordlist_to_bytes(words: &[&str]) -> Vec<u8> {
    let mut data = Vec::new();
    let mut buf: u32 = 0;
    let mut buf_len: usize = 0;

    for word in words {
        let index = EFF_LARGE_WORDLIST[..ENCODING_SIZE]
            .iter()
            .position(|(_, w)| w.eq_ignore_ascii_case(word))
            .expect("Unknown Diceware word") as u32;
        buf = (buf << 12) | index;
        buf_len += 12;
        while buf_len >= 8 {
            buf_len -= 8;
            data.push(((buf >> buf_len) & 0xFF) as u8);
        }
    }
    // Any remaining bits are trailing padding zeros; discard them.

    if data.len() < 4 {
        return Vec::new();
    }
    let len = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
    data[4..][..len].to_vec()
}

#[cfg(test)]
mod test {
    use super::{
        bytes_to_wordlist, wordlist_to_bytes, DICEWARE_INSTRUCTIONS, EFF_LARGE_WORDLIST,
        ENCODING_SIZE,
    };

    #[test]
    fn validate_wordlist_large_enough() {
        assert!(
            EFF_LARGE_WORDLIST.len() >= ENCODING_SIZE,
            "EFF Large wordlist must have at least {} entries",
            ENCODING_SIZE
        );
        EFF_LARGE_WORDLIST[..ENCODING_SIZE]
            .iter()
            .for_each(|(_, w)| assert!(!w.is_empty()));
    }

    #[test]
    fn validate_instructions_non_empty() {
        assert!(!DICEWARE_INSTRUCTIONS.is_empty());
    }

    #[test]
    fn validate_roundtrip_short() {
        let original: Vec<u8> = vec![0x85, 0xc4, 0x3e, 0xe0, 0x38, 0x57, 0x76, 0x5b];
        let words = bytes_to_wordlist(&original);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_unaligned() {
        // 7 bytes — not on a 12-bit boundary, exercises zero-padding
        let original: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7];
        let words = bytes_to_wordlist(&original);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_empty() {
        let original: Vec<u8> = vec![];
        let words = bytes_to_wordlist(&original);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }
}