artifactize-provider 0.27.2

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Decode JSON and URL escape layers without losing the original spans.

use std::ops::Range;

/// Match any JSON nesting serde_json admits, then withhold pathological deeper input.
const MAX_LAYERS: usize = 128;

fn json_escape(bytes: &[u8]) -> Option<(char, usize)> {
    let simple = match *bytes.get(1)? {
        b'"' => '"',
        b'\\' => '\\',
        b'/' => '/',
        b'b' => '\u{8}',
        b'f' => '\u{c}',
        b'n' => '\n',
        b'r' => '\r',
        b't' => '\t',
        b'u' => {
            let high = hex(bytes.get(2..6)?)?;
            if !(0xd800..=0xdbff).contains(&high) {
                return char::from_u32(high).map(|character| (character, 6));
            }
            if bytes.get(6..8)? != b"\\u" {
                return None;
            }
            let low = hex(bytes.get(8..12)?)?;
            if !(0xdc00..=0xdfff).contains(&low) {
                return None;
            }
            return char::from_u32(0x10000 + ((high - 0xd800) << 10) + low - 0xdc00)
                .map(|character| (character, 12));
        }
        _ => return None,
    };
    Some((simple, 2))
}

fn hex(bytes: &[u8]) -> Option<u32> {
    bytes.iter().try_fold(0, |value, &digit| {
        Some((value << 4) | char::from(digit).to_digit(16)?)
    })
}

fn percent_byte(bytes: &[u8]) -> Option<u8> {
    (bytes.first() == Some(&b'%')).then_some(())?;
    u8::try_from(hex(bytes.get(1..3)?)?).ok()
}

fn url_escape(bytes: &[u8]) -> Option<(char, usize)> {
    let first = percent_byte(bytes)?;
    let width = match first {
        0..=0x7f => 1,
        0xc2..=0xdf => 2,
        0xe0..=0xef => 3,
        0xf0..=0xf4 => 4,
        _ => return None,
    };
    let mut scalar = [0; 4]; // UTF-8 uses at most four bytes per scalar.
    scalar[0] = first;
    for (index, byte) in scalar[..width].iter_mut().enumerate().skip(1) {
        *byte = percent_byte(bytes.get(index * 3..)?)?;
    }
    let character = std::str::from_utf8(&scalar[..width]).ok()?.chars().next()?;
    Some((character, width * 3))
}

pub(crate) const MARKERS: [char; 2] = ['\\', '%'];

/// Visit each different spelling. `offsets` maps the start of a scalar (or the end
/// of the string) back into the original. Escape recognition also works inside
/// prose, JSON fragments, and strings containing more serialized values.
fn decoded(text: &str, mut visit: impl FnMut(&str, &[usize]) -> bool) -> bool {
    if !text.contains(MARKERS) {
        return false;
    }
    let mut text = text.to_owned();
    let mut offsets = Vec::new();
    for _ in 0..MAX_LAYERS {
        let mut next = String::with_capacity(text.len());
        let mut map = Vec::with_capacity(text.len() + 1);
        let mut index = 0;
        let original = |index| offsets.get(index).copied().unwrap_or(index);
        while index < text.len() {
            let rest = &text[index..];
            let ch = rest.chars().next().expect("index is a scalar boundary");
            let (replacement, consumed) = match ch {
                '\\' => json_escape(rest.as_bytes()),
                '%' => url_escape(rest.as_bytes()),
                _ => None,
            }
            .unwrap_or((ch, ch.len_utf8()));
            next.push(replacement);
            map.extend(std::iter::repeat_n(original(index), replacement.len_utf8()));
            index += consumed;
        }
        if next == text {
            return false;
        }
        map.push(original(index));
        if visit(&next, &map) {
            return true;
        }
        if !next.contains(MARKERS) {
            return false;
        }
        text = next;
        offsets = map;
    }
    true
}

pub(super) fn matches(text: &str, predicate: impl Fn(&str) -> bool) -> bool {
    predicate(text) || decoded(text, |decoded, _| predicate(decoded))
}

// Collect all spellings before replacing any of them; replacing a substring at
// one layer must not hide an overlapping match at another layer.
pub(super) fn spans(text: &str, values: &[String]) -> Option<Vec<Range<usize>>> {
    let mut ranges = Vec::new();
    let mut record = |text: &str, map: &[usize]| {
        let original = |index| map.get(index).copied().unwrap_or(index);
        let mut layer = Vec::new();
        for (start, _) in text.char_indices() {
            if let Some(length) = values
                .iter()
                .filter(|value| text[start..].starts_with(value.as_str()))
                .map(String::len)
                .max()
            {
                merge_range(&mut layer, original(start)..original(start + length));
            }
        }
        ranges.extend(layer);
        false
    };
    record(text, &[]);
    if decoded(text, record) {
        return None;
    }
    ranges.sort_unstable_by_key(|range| (range.start, range.end));
    let mut merged = Vec::new();
    for range in ranges {
        merge_range(&mut merged, range);
    }
    Some(merged)
}

fn merge_range(ranges: &mut Vec<Range<usize>>, range: Range<usize>) {
    match ranges.last_mut() {
        Some(last) if range.start < last.end => last.end = last.end.max(range.end),
        _ => ranges.push(range),
    }
}