use super::{FormatKind, Piece, PieceKind};
pub fn pieces_in(literal: &str, kind: FormatKind, out: &mut Vec<Piece>) {
let Some(body) = body_of(literal) else {
return;
};
match kind {
FormatKind::Std => scan_the_std_form(literal, body, out),
FormatKind::Printf => scan_the_c_form(literal, body, out, FormatKind::Printf),
FormatKind::Scanf => scan_the_c_form(literal, body, out, FormatKind::Scanf),
}
}
#[derive(Debug, Clone, Copy)]
struct Body {
start: usize,
end: usize,
raw: bool,
}
fn body_of(literal: &str) -> Option<Body> {
let bytes = literal.as_bytes();
const PREFIXES: &[&str] = &["u8R", "LR", "uR", "UR", "R", "u8", "L", "u", "U", ""];
let at = PREFIXES.iter().find_map(|prefix| {
let length = prefix.len();
(bytes.len() > length && bytes.starts_with(prefix.as_bytes()) && bytes[length] == b'"')
.then_some(length)
})?;
let raw = literal.get(..at).is_some_and(|prefix| prefix.contains('R'));
let at = at + 1;
if !raw {
let end = if bytes.len() > at && bytes[bytes.len() - 1] == b'"' {
bytes.len() - 1
} else {
bytes.len()
};
return Some(Body {
start: at,
end,
raw,
});
}
let open = literal.get(at..)?.find('(')? + at;
let delimiter = literal.get(at..open)?;
let closing = format!("){delimiter}\"");
let end = if let Some(body) = literal.get(open + 1..) {
if body.ends_with(&closing) {
literal.len() - closing.len()
} else {
literal.len()
}
} else {
literal.len()
};
Some(Body {
start: open + 1,
end: end.max(open + 1),
raw,
})
}
fn byte_at(text: &str, at: usize) -> Option<u8> {
text.as_bytes().get(at).copied()
}
fn step(text: &str, at: usize) -> usize {
text.get(at..)
.and_then(|rest| rest.chars().next())
.map_or(1, char::len_utf8)
}
const PRINTF_CONVERSIONS: &[u8] = b"diouxXeEfFgGaAcspnm";
const SCANF_CONVERSIONS: &[u8] = b"diouxXeEfFgGaAcspn";
const STD_CONVERSIONS: &[u8] = b"aAbBcdeEfFgGopPsxX?";
fn scan_the_std_form(text: &str, body: Body, out: &mut Vec<Piece>) {
let mut at = body.start;
while at < body.end {
match byte_at(text, at) {
Some(b'{') if byte_at(text, at + 1) == Some(b'{') => {
push(out, PieceKind::Escape, at, at + 2);
at += 2;
}
Some(b'}') if byte_at(text, at + 1) == Some(b'}') => {
push(out, PieceKind::Escape, at, at + 2);
at += 2;
}
Some(b'{') => at = scan_a_std_field(text, at, body.end, out),
Some(b'\\') if !body.raw => at = (at + 2).min(body.end),
_ => at += step(text, at),
}
}
}
fn scan_a_std_field(text: &str, open: usize, end: usize, out: &mut Vec<Piece>) -> usize {
push(out, PieceKind::Specifier, open, open + 1);
let mut at = open + 1;
if at >= end {
return end;
}
let argument_from = at;
if byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
while byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
} else if byte_at(text, at).is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic()) {
while byte_at(text, at).is_some_and(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) {
at += 1;
}
}
if at > argument_from {
push(out, PieceKind::Argument, argument_from, at);
}
if at >= end {
return end;
}
match byte_at(text, at) {
Some(b'}') => {
push(out, PieceKind::Specifier, at, at + 1);
at + 1
}
Some(b':') => {
push(out, PieceKind::Specifier, at, at + 1);
let after_the_spec = scan_a_std_spec(text, at + 1, end, out);
if after_the_spec < end && byte_at(text, after_the_spec) == Some(b'}') {
push(
out,
PieceKind::Specifier,
after_the_spec,
after_the_spec + 1,
);
after_the_spec + 1
} else {
after_the_spec
}
}
_ => {
let close = find(text, at, end, b'}').unwrap_or(end);
push(out, PieceKind::Specifier, at, close);
if close < end {
push(out, PieceKind::Specifier, close, close + 1);
close + 1
} else {
close
}
}
}
}
fn scan_a_std_spec(text: &str, from: usize, end: usize, out: &mut Vec<Piece>) -> usize {
let mut at = from;
let align_from = at;
if !matches!(byte_at(text, at), Some(b'<') | Some(b'>') | Some(b'^')) {
let second = at + step(text, at);
if matches!(byte_at(text, second), Some(b'<') | Some(b'>') | Some(b'^')) {
at = second;
}
}
if matches!(at, _ if byte_at(text, at).is_some_and(|b| matches!(b, b'<' | b'>' | b'^'))) {
at += 1;
push(out, PieceKind::Specifier, align_from, at);
}
while let Some(byte) = byte_at(text, at) {
if !matches!(byte, b'+' | b'-' | b' ' | b'#' | b'0') {
break;
}
push(out, PieceKind::Specifier, at, at + 1);
at += 1;
}
if byte_at(text, at) == Some(b'{') {
at = scan_a_dynamic_width(text, at, end, out);
} else {
let width_from = at;
while byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
if at > width_from {
push(out, PieceKind::Specifier, width_from, at);
}
}
if byte_at(text, at) == Some(b'.') {
push(out, PieceKind::Specifier, at, at + 1);
at += 1;
if byte_at(text, at) == Some(b'{') {
at = scan_a_dynamic_width(text, at, end, out);
} else {
let digits_from = at;
while byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
if at > digits_from {
push(out, PieceKind::Specifier, digits_from, at);
}
}
}
if byte_at(text, at) == Some(b'L') {
push(out, PieceKind::Specifier, at, at + 1);
at += 1;
}
if let Some(byte) = byte_at(text, at)
&& STD_CONVERSIONS.contains(&byte)
{
push(out, PieceKind::Conversion, at, at + 1);
at += 1;
}
at
}
fn scan_a_dynamic_width(text: &str, open: usize, end: usize, out: &mut Vec<Piece>) -> usize {
let mut at = open + 1;
while at < end && byte_at(text, at) != Some(b'}') {
at += step(text, at);
}
let close = if at < end { at + 1 } else { end };
push(out, PieceKind::DynamicWidth, open, close);
close
}
fn scan_the_c_form(text: &str, body: Body, out: &mut Vec<Piece>, kind: FormatKind) {
let mut at = body.start;
while at < body.end {
match byte_at(text, at) {
Some(b'\\') if !body.raw => at = (at + 2).min(body.end),
Some(b'%') => {
if byte_at(text, at + 1) == Some(b'%') {
push(out, PieceKind::Escape, at, at + 2);
at += 2;
continue;
}
match scan_a_c_conversion(text, at, body.end, out, kind) {
Some(after) => at = after,
None => at += 1,
}
}
_ => at += step(text, at),
}
}
}
fn scan_a_c_conversion(
text: &str,
from: usize,
end: usize,
out: &mut Vec<Piece>,
kind: FormatKind,
) -> Option<usize> {
let mark = out.len();
let tail = out.last().map(|piece| (piece.kind, piece.end));
let conversion = scan_a_c_conversion_inner(text, from, end, out, kind);
if conversion.is_none() {
out.truncate(mark);
if let Some((kind, end)) = tail
&& let Some(last) = out.last_mut()
&& last.kind == kind
{
last.end = end;
}
}
conversion
}
fn scan_a_c_conversion_inner(
text: &str,
from: usize,
end: usize,
out: &mut Vec<Piece>,
kind: FormatKind,
) -> Option<usize> {
let mut at = from;
push(out, PieceKind::Specifier, at, at + 1);
at += 1;
if at >= end {
return None;
}
if kind == FormatKind::Printf {
let digits_from = at;
let mut after_digits = at;
while byte_at(text, after_digits).is_some_and(|byte| byte.is_ascii_digit()) {
after_digits += 1;
}
if after_digits > digits_from && byte_at(text, after_digits) == Some(b'$') {
push(out, PieceKind::Argument, digits_from, after_digits + 1);
at = after_digits + 1;
}
}
if kind == FormatKind::Printf {
let flags_from = at;
while byte_at(text, at).is_some_and(|byte| matches!(byte, b'-' | b'+' | b' ' | b'#' | b'0'))
{
at += 1;
}
if at > flags_from {
push(out, PieceKind::Specifier, flags_from, at);
}
}
if byte_at(text, at) == Some(b'*') {
push(out, PieceKind::Argument, at, at + 1);
at += 1;
} else {
let width_from = at;
while byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
if at > width_from {
push(out, PieceKind::Specifier, width_from, at);
}
}
if kind == FormatKind::Printf && byte_at(text, at) == Some(b'.') {
push(out, PieceKind::Specifier, at, at + 1);
at += 1;
if byte_at(text, at) == Some(b'*') {
push(out, PieceKind::Argument, at, at + 1);
at += 1;
} else {
let digits_from = at;
while byte_at(text, at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
if at > digits_from {
push(out, PieceKind::Specifier, digits_from, at);
}
}
}
let length_from = at;
match byte_at(text, at) {
Some(b'h') | Some(b'l') => {
let doubled = byte_at(text, at + 1) == byte_at(text, at);
at += if doubled { 2 } else { 1 };
}
Some(b'j') | Some(b'z') | Some(b't') | Some(b'L') => at += 1,
_ => {}
}
if at > length_from {
push(out, PieceKind::Specifier, length_from, at);
}
if kind == FormatKind::Scanf && byte_at(text, at) == Some(b'[') {
let set_from = at;
at += 1;
if byte_at(text, at) == Some(b'^') {
at += 1;
}
if byte_at(text, at) == Some(b']') {
at += 1;
}
while at < end && byte_at(text, at) != Some(b']') {
at += if byte_at(text, at) == Some(b'\\') {
2
} else {
1
};
}
let close = if at < end { at + 1 } else { end };
push(out, PieceKind::Conversion, set_from, close);
return Some(close);
}
let byte = byte_at(text, at)?;
let known = match kind {
FormatKind::Printf => PRINTF_CONVERSIONS.contains(&byte),
FormatKind::Scanf => SCANF_CONVERSIONS.contains(&byte),
FormatKind::Std => false,
};
if !known {
return None;
}
push(out, PieceKind::Conversion, at, at + 1);
Some(at + 1)
}
fn push(out: &mut Vec<Piece>, kind: PieceKind, start: usize, end: usize) {
if end <= start {
return;
}
if let Some(last) = out.last_mut()
&& last.kind == kind
&& last.end == start
{
last.end = end;
return;
}
out.push(Piece { kind, start, end });
}
fn find(text: &str, from: usize, to: usize, needle: u8) -> Option<usize> {
let bytes = text.as_bytes();
let mut at = from;
while at < to {
if bytes.get(at).copied() == Some(needle) {
return Some(at);
}
at += 1;
}
None
}