typeward 0.6.0

A type-driven parser combinator library for Rust.
Documentation
use crate::error::{ParseError, ParseResult};
use stable_pattern::{Pattern, Searcher};

pub(super) fn checked_consumed_len(
    input_len: usize,
    end_len: usize,
    input_name: &str,
) -> ParseResult<usize> {
    if end_len > input_len {
        return Err(ParseError::fatal(format!(
            "invalid input bounds while slicing {input_name} input"
        )));
    }

    Ok(input_len - end_len)
}

pub(super) fn take_while_prefix_len<P>(input: &str, predicate: P) -> usize
where
    P: for<'a> Pattern<'a> + Copy,
{
    let mut idx = 0;
    while let Some(rest) = predicate.strip_prefix_of(&input[idx..]) {
        let matched = input[idx..].len() - rest.len();
        if matched == 0 {
            break;
        }
        idx += matched;
    }
    idx
}

pub(super) const fn utf8_char_width(first: u8) -> usize {
    if first < 0x80 {
        1
    } else if (first & 0b1110_0000) == 0b1100_0000 {
        2
    } else if (first & 0b1111_0000) == 0b1110_0000 {
        3
    } else if (first & 0b1111_1000) == 0b1111_0000 {
        4
    } else {
        0
    }
}

/// Returns the valid UTF-8 prefix of `bytes` without requiring the entire
/// remaining slice to be valid.
pub(super) fn valid_utf8_prefix(bytes: &[u8]) -> &str {
    let valid_len = match std::str::from_utf8(bytes) {
        Ok(_) => bytes.len(),
        Err(err) => err.valid_up_to(),
    };

    std::str::from_utf8(&bytes[..valid_len]).expect("the valid_up_to prefix should be valid UTF-8")
}

pub(super) fn take_char_prefix(bytes: &[u8]) -> ParseResult<Option<(char, usize)>> {
    let Some(&first) = bytes.first() else {
        return Ok(None);
    };

    let width = utf8_char_width(first);
    if width == 0 {
        return Err(ParseError::fatal(
            "invalid UTF-8 input: invalid leading byte",
        ));
    }

    if bytes.len() < width {
        return Err(ParseError::fatal(
            "invalid UTF-8 input: unexpected end of byte input",
        ));
    }

    let s = std::str::from_utf8(&bytes[..width])
        .map_err(|err| ParseError::fatal(format!("invalid UTF-8 input: {err}")))?;
    let ch = s
        .chars()
        .next()
        .expect("validated UTF-8 character should exist");
    Ok(Some((ch, width)))
}

pub(super) fn trim_start_utf8_len(bytes: &[u8]) -> usize {
    let valid = valid_utf8_prefix(bytes);
    valid.len() - valid.trim_start().len()
}

pub(super) fn split_take_till<'a, P>(input: &'a str, predicate: P) -> (&'a str, &'a str)
where
    P: for<'b> Pattern<'b> + Copy,
{
    predicate
        .into_searcher(input)
        .next_match()
        .map_or((input, ""), |(start, _)| input.split_at(start))
}