stringcue 0.1.0

String Compressed Unicode Encoding - encode unicode more space efficient than utf-8 by sacrificing robustness like byte-boundaries.
Documentation
//! Encoding of strings into compact stringcue blobs.
//!
//! Codepoints are written in the smallest length class that fits them;
//! larger encodings of the same codepoint are invalid and rejected by
//! [`crate::decode`] as corruption.

use crate::options::{EncodeEmpties, EncodeOptions, EncodeTerminator};
use crate::prefix::Prefix;
use alloc::vec::Vec;
use arbitrary_int::{u3, u7};
use bitstream_io::{BigEndian, BitWrite, BitWriter};

/// Encodes a single string as a stringcue blob.
///
/// # Examples
///
/// ```no_run
/// let encoded = stringcue::encode("Hello, world!", Default::default());
/// let decoded = stringcue::decode(&encoded, Default::default()).expect("decoding should roundtrip encoding");
///
/// assert_eq!(decoded, "Hello, world!");
/// ```
pub fn encode(input: impl AsRef<str>, options: EncodeOptions) -> Vec<u8> {
    let mut writer = BitWriter::endian(Vec::new(), BigEndian);
    let mut bits = write_string(&mut writer, input.as_ref());
    if options.terminator == EncodeTerminator::Write {
        bits += write_control(&mut writer);
    }
    write_padding(&mut writer, bits);
    writer.into_writer()
}

/// Encodes a container of strings as one compact stringcue blob.
///
/// Strings are separated by the special `CONTROL` value. Whether a
/// `CONTROL` terminator is appended depends on the given `options`; with
/// the default options it is not.
///
/// # Examples
///
/// ```no_run
/// let strings = ["Hello", "world", "¡hola, unicode!"];
///
/// let blob = stringcue::encode_all(&strings, Default::default());
/// let decoded: Vec<String> = stringcue::decode_all(&blob, Default::default()).expect("decoding should roundtrip encoding").collect();
///
/// assert_eq!(decoded, strings);
/// ```
pub fn encode_all<I, T>(input: I, options: EncodeOptions) -> Vec<u8>
where
    I: IntoIterator<Item = T>,
    T: AsRef<str>,
{
    let (skip_empties, terminate) = match options.terminator {
        EncodeTerminator::Write => (true, true),
        EncodeTerminator::Omit(empties) => (empties == EncodeEmpties::Skip, false),
    };

    let mut writer = BitWriter::endian(Vec::new(), BigEndian);
    let mut bits = 0;
    let mut first = true;
    for string in input {
        let string = string.as_ref();
        if skip_empties && string.is_empty() {
            continue;
        }
        if !first {
            bits += write_control(&mut writer);
        }
        first = false;
        bits += write_string(&mut writer, string);
    }
    if terminate {
        bits += write_control(&mut writer);
        bits += write_control(&mut writer);
    }
    write_padding(&mut writer, bits);
    writer.into_writer()
}

/// The bit width of the tail field of each length class and the total
/// width of the codepoint field it completes, ordered so the first class
/// that fits a codepoint is the cheapest.
const TAIL_BITS: [(u32, u32); 4] = [(7, 10), (8, 11), (13, 16), (18, 21)];

/// Writes a single codepoint and returns the number of bits written.
fn write_codepoint(writer: &mut impl BitWrite, codepoint: u32) -> u64 {
    if (0x20..0x7F).contains(&codepoint) {
        return write_bits(
            writer,
            7,
            u64::from(Prefix::Ascii(u7::new(codepoint as u8)).to_bits().value()),
        );
    }

    let width = 32 - codepoint.leading_zeros();
    let &(tail_bits, field_width) = TAIL_BITS
        .iter()
        .find(|&&(_, total)| width <= total)
        .expect("every codepoint fits the largest length class");
    let payload = u3::new((codepoint >> (field_width - 3)) as u8);
    let prefix = match tail_bits {
        7 => Prefix::Tail7 { payload },
        8 => Prefix::Tail8 { payload },
        13 => Prefix::Tail13 { payload },
        _ => Prefix::Tail18 { payload },
    };
    write_bits(writer, 7, u64::from(prefix.to_bits().value()));
    let tail_mask = (1 << tail_bits) - 1;
    7 + write_bits(writer, tail_bits, u64::from(codepoint & tail_mask))
}

/// Writes the `CONTROL` value and returns the number of bits written.
fn write_control(writer: &mut impl BitWrite) -> u64 {
    write_bits(writer, 7, u64::from(Prefix::Control.to_bits().value()))
}

/// Writes a whole string codepoint by codepoint and returns the number of
/// bits written.
fn write_string(writer: &mut impl BitWrite, string: &str) -> u64 {
    string
        .chars()
        .map(|c| write_codepoint(writer, c as u32))
        .sum()
}

/// Writes 1 bits up to the next byte boundary after the given number of
/// written bits.
fn write_padding(writer: &mut impl BitWrite, bits: u64) {
    let padding = ((8 - bits % 8) % 8) as u32;
    if padding > 0 {
        write_bits(writer, padding, (1 << padding) - 1);
    }
}

/// Writes `bits` bits of an unsigned value, most significant bit first, and
/// returns the number of bits written.
fn write_bits(writer: &mut impl BitWrite, bits: u32, value: u64) -> u64 {
    writer
        .write_unsigned_var(bits, value)
        .expect("writing to a byte buffer cannot fail");
    u64::from(bits)
}

#[cfg(test)]
mod tests;