use super::event::{
CsiDispatch, EscDispatch, Handler, OscDispatch, StringDispatch, StringKind, StringTermination,
};
use super::params::Params;
use super::utf8::{PushResult, Utf8Decoder};
const DEFAULT_MAX_STRING_BYTES: usize = 4 * 1024;
const DEFAULT_MAX_PARAMETERS: usize = 32;
const DEFAULT_MAX_INTERMEDIATES: usize = 16;
const MAX_PARAMETER_BYTES_PER_VALUE: usize = 64;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
Ground,
Escape,
EscapeIntermediate,
CsiEntry,
CsiParameter,
CsiIntermediate,
CsiIgnore,
DcsEntry,
DcsParameter,
DcsIntermediate,
DcsPassthrough,
DcsIgnore,
String,
StringEscape,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParserOptions {
pub max_string_bytes: usize,
pub max_parameters: usize,
pub max_intermediates: usize,
}
impl Default for ParserOptions {
fn default() -> Self {
Self {
max_string_bytes: DEFAULT_MAX_STRING_BYTES,
max_parameters: DEFAULT_MAX_PARAMETERS,
max_intermediates: DEFAULT_MAX_INTERMEDIATES,
}
}
}
#[derive(Debug)]
pub struct Parser {
options: ParserOptions,
state: State,
utf8: Utf8Decoder,
intermediates: Vec<u8>,
private_markers: Vec<u8>,
parameters: Vec<u8>,
parameter_count: usize,
parameter_bytes: usize,
sequence_truncated: bool,
string_kind: Option<StringKind>,
string_final: Option<u8>,
string_data: Vec<u8>,
string_truncated: bool,
}
impl Default for Parser {
fn default() -> Self {
Self::new()
}
}
impl Parser {
#[must_use]
pub fn new() -> Self {
Self::with_options(ParserOptions::default())
}
#[must_use]
pub fn with_options(options: ParserOptions) -> Self {
Self {
options,
state: State::Ground,
utf8: Utf8Decoder::new(),
intermediates: Vec::new(),
private_markers: Vec::new(),
parameters: Vec::new(),
parameter_count: 0,
parameter_bytes: 0,
sequence_truncated: false,
string_kind: None,
string_final: None,
string_data: Vec::new(),
string_truncated: false,
}
}
#[must_use]
pub const fn options(&self) -> ParserOptions {
self.options
}
pub fn advance<H: Handler + ?Sized>(&mut self, handler: &mut H, bytes: &[u8]) {
for &byte in bytes {
let mut reprocess = true;
while reprocess {
reprocess = self.process_byte(handler, byte);
}
}
}
pub fn finish<H: Handler + ?Sized>(&mut self, handler: &mut H) {
if self.utf8.finish() {
handler.print('\u{FFFD}');
}
self.clear_sequence();
}
pub fn reset(&mut self) {
self.utf8.reset();
self.clear_sequence();
}
fn process_byte<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) -> bool {
if byte == 0x7F && self.state != State::Ground {
return false;
}
match self.state {
State::Ground => self.process_ground(handler, byte),
State::Escape => {
self.process_escape(handler, byte);
false
}
State::EscapeIntermediate => {
self.process_escape_intermediate(handler, byte);
false
}
State::CsiEntry => {
self.process_csi_entry(handler, byte);
false
}
State::CsiParameter => {
self.process_csi_parameter(handler, byte);
false
}
State::CsiIntermediate => {
self.process_csi_intermediate(handler, byte);
false
}
State::CsiIgnore => {
self.process_csi_ignore(handler, byte);
false
}
State::DcsEntry => {
self.process_dcs_entry(handler, byte);
false
}
State::DcsParameter => {
self.process_dcs_parameter(handler, byte);
false
}
State::DcsIntermediate => {
self.process_dcs_intermediate(handler, byte);
false
}
State::DcsPassthrough | State::String => {
self.process_string(handler, byte);
false
}
State::DcsIgnore => {
self.process_dcs_ignore(handler, byte);
false
}
State::StringEscape => self.process_string_escape(handler, byte),
}
}
fn process_ground<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) -> bool {
if self.utf8.is_pending() {
match self.utf8.push(byte) {
PushResult::NeedMore => return false,
PushResult::Character(character) => {
self.dispatch_decoded_character(handler, character);
return false;
}
PushResult::Invalid => {
handler.print('\u{FFFD}');
return false;
}
PushResult::InvalidAndReprocess => {
handler.print('\u{FFFD}');
return true;
}
}
}
match byte {
0x00..=0x1F | 0x7F => {
self.process_ground_control(handler, byte);
false
}
0x20..=0x7E => {
handler.print(char::from(byte));
false
}
0x80..=0x9F => {
self.process_ground_c1(handler, byte);
false
}
_ => match self.utf8.push(byte) {
PushResult::NeedMore => false,
PushResult::Character(character) => {
self.dispatch_decoded_character(handler, character);
false
}
PushResult::Invalid | PushResult::InvalidAndReprocess => {
handler.print('\u{FFFD}');
false
}
},
}
}
fn dispatch_decoded_character<H: Handler + ?Sized>(
&mut self,
handler: &mut H,
character: char,
) {
let value = u32::from(character);
if value <= 0x1F || value == 0x7F {
let byte = u8::try_from(value).expect("C0 control code point fits in one byte");
self.process_ground_control(handler, byte);
} else if value <= 0x9F {
let byte = u8::try_from(value).expect("C1 control code point fits in one byte");
self.process_ground_c1(handler, byte);
} else {
handler.print(character);
}
}
fn process_ground_control<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
match byte {
0x1B => self.start_escape(),
0x7F => {}
_ => handler.execute(byte),
}
}
fn process_ground_c1<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
match byte {
0x90 => self.start_string(StringKind::Dcs),
0x98 => self.start_string(StringKind::Sos),
0x9B => self.start_csi(),
0x9D => self.start_string(StringKind::Osc),
0x9E => self.start_string(StringKind::Pm),
0x9F => self.start_string(StringKind::Apc),
_ => handler.execute(byte),
}
}
fn start_c1_sequence(&mut self, byte: u8) -> bool {
match byte {
0x90 => self.start_string(StringKind::Dcs),
0x98 => self.start_string(StringKind::Sos),
0x9B => self.start_csi(),
0x9D => self.start_string(StringKind::Osc),
0x9E => self.start_string(StringKind::Pm),
0x9F => self.start_string(StringKind::Apc),
_ => return false,
}
true
}
fn process_active_c1<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) -> bool {
if self.start_c1_sequence(byte) {
true
} else if (0x80..=0x9F).contains(&byte) {
handler.execute(byte);
true
} else {
false
}
}
fn process_escape<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
b'[' => self.start_csi(),
b']' => self.start_string(StringKind::Osc),
b'P' => self.start_string(StringKind::Dcs),
b'X' => self.start_string(StringKind::Sos),
b'^' => self.start_string(StringKind::Pm),
b'_' => self.start_string(StringKind::Apc),
0x20..=0x2F => {
self.add_intermediate(byte);
self.state = State::EscapeIntermediate;
}
0x30..=0x7E => self.dispatch_esc(handler, byte),
_ => handler.execute(byte),
}
}
fn process_escape_intermediate<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
0x20..=0x2F => self.add_intermediate(byte),
0x30..=0x7E => self.dispatch_esc(handler, byte),
_ => handler.execute(byte),
}
}
fn process_csi_entry<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
0x30..=0x3F => {
if is_private_marker(byte) && self.parameters.is_empty() {
self.add_private_marker(byte);
} else {
self.add_parameter(byte);
}
self.state = if self.sequence_truncated {
State::CsiIgnore
} else {
State::CsiParameter
};
}
0x20..=0x2F => {
self.add_intermediate(byte);
self.state = if self.sequence_truncated {
State::CsiIgnore
} else {
State::CsiIntermediate
};
}
0x40..=0x7E => self.dispatch_csi(handler, byte),
_ => handler.execute(byte),
}
}
fn process_csi_parameter<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
0x30..=0x3F => {
self.add_parameter(byte);
if self.sequence_truncated {
self.state = State::CsiIgnore;
}
}
0x20..=0x2F => {
self.add_intermediate(byte);
self.state = if self.sequence_truncated {
State::CsiIgnore
} else {
State::CsiIntermediate
};
}
0x40..=0x7E => self.dispatch_csi(handler, byte),
_ => handler.execute(byte),
}
}
fn process_csi_intermediate<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
0x20..=0x2F => self.add_intermediate(byte),
0x40..=0x7E => self.dispatch_csi(handler, byte),
0x30..=0x3F => {
self.sequence_truncated = true;
self.state = State::CsiIgnore;
}
_ => handler.execute(byte),
}
}
fn process_csi_ignore<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.process_active_c1(handler, byte) {
return;
}
match byte {
0x1B => self.start_escape(),
0x40..=0x7E => self.dispatch_csi(handler, byte),
_ => handler.execute(byte),
}
}
fn process_dcs_entry<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return;
}
if self.start_c1_sequence(byte) {
return;
}
match byte {
0x1B => self.state = State::StringEscape,
0x30..=0x3F => {
if is_private_marker(byte) && self.parameters.is_empty() {
self.add_private_marker(byte);
} else {
self.add_parameter(byte);
}
self.state = if self.sequence_truncated {
State::DcsIgnore
} else {
State::DcsParameter
};
}
0x20..=0x2F => {
self.add_intermediate(byte);
self.state = if self.sequence_truncated {
State::DcsIgnore
} else {
State::DcsIntermediate
};
}
0x40..=0x7E => self.string_final = Some(byte),
0x00..=0x1F => handler.execute(byte),
_ => {
self.sequence_truncated = true;
self.state = State::DcsIgnore;
}
}
if self.string_final.is_some() {
self.state = State::DcsPassthrough;
}
}
fn process_dcs_parameter<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return;
}
if self.start_c1_sequence(byte) {
return;
}
match byte {
0x1B => self.state = State::StringEscape,
0x30..=0x3F => {
self.add_parameter(byte);
if self.sequence_truncated {
self.state = State::DcsIgnore;
}
}
0x20..=0x2F => {
self.add_intermediate(byte);
self.state = if self.sequence_truncated {
State::DcsIgnore
} else {
State::DcsIntermediate
};
}
0x40..=0x7E => {
self.string_final = Some(byte);
self.state = State::DcsPassthrough;
}
0x00..=0x1F => handler.execute(byte),
_ => {
self.sequence_truncated = true;
self.state = State::DcsIgnore;
}
}
}
fn process_dcs_intermediate<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return;
}
if self.start_c1_sequence(byte) {
return;
}
match byte {
0x1B => self.state = State::StringEscape,
0x20..=0x2F => self.add_intermediate(byte),
0x40..=0x7E => {
self.string_final = Some(byte);
self.state = State::DcsPassthrough;
}
0x00..=0x1F => handler.execute(byte),
_ => {
self.sequence_truncated = true;
self.state = State::DcsIgnore;
}
}
}
fn process_dcs_ignore<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return;
}
if self.start_c1_sequence(byte) {
return;
}
match byte {
0x1B => self.state = State::StringEscape,
0x40..=0x7E if self.string_final.is_none() => {
self.string_final = Some(byte);
}
0x00..=0x1F | 0x80..=0x9F => handler.execute(byte),
_ => {}
}
}
fn process_string<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) {
if Self::is_cancel(byte) {
self.clear_sequence();
return;
}
if self.start_c1_sequence(byte) {
return;
}
if byte == 0x1B {
self.state = State::StringEscape;
return;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return;
}
if self.string_kind == Some(StringKind::Osc) && byte == 0x07 {
self.dispatch_string(handler, StringTermination::Bell);
return;
}
if byte < 0x20 || (0x80..=0x9F).contains(&byte) {
handler.execute(byte);
return;
}
self.append_string(byte);
}
fn process_string_escape<H: Handler + ?Sized>(&mut self, handler: &mut H, byte: u8) -> bool {
if Self::is_cancel(byte) {
self.clear_sequence();
return false;
}
if self.start_c1_sequence(byte) {
return false;
}
if byte == 0x9C {
self.dispatch_string(handler, StringTermination::St);
return false;
}
match byte {
b'\\' => {
self.dispatch_string(handler, StringTermination::St);
false
}
0x1B => false,
_ => {
self.clear_sequence();
self.start_escape();
true
}
}
}
fn dispatch_esc<H: Handler + ?Sized>(&mut self, handler: &mut H, final_byte: u8) {
let event = EscDispatch {
final_byte,
intermediates: &self.intermediates,
truncated: self.sequence_truncated,
};
handler.esc_dispatch(event);
self.clear_sequence();
}
fn dispatch_csi<H: Handler + ?Sized>(&mut self, handler: &mut H, final_byte: u8) {
let event = CsiDispatch {
final_byte,
private_markers: &self.private_markers,
params: Params::new(&self.parameters),
intermediates: &self.intermediates,
truncated: self.sequence_truncated,
};
handler.csi_dispatch(event);
self.clear_sequence();
}
fn dispatch_string<H: Handler + ?Sized>(
&mut self,
handler: &mut H,
termination: StringTermination,
) {
let Some(kind) = self.string_kind else {
self.clear_sequence();
return;
};
if kind == StringKind::Osc {
let event = OscDispatch {
data: &self.string_data,
termination,
truncated: self.string_truncated,
};
handler.osc_dispatch(event);
} else {
let event = StringDispatch {
kind,
final_byte: self.string_final,
private_markers: &self.private_markers,
params: Params::new(&self.parameters),
intermediates: &self.intermediates,
data: &self.string_data,
termination,
truncated: self.string_truncated || self.sequence_truncated,
};
handler.string_dispatch(event);
}
self.clear_sequence();
}
fn start_escape(&mut self) {
self.clear_sequence();
self.state = State::Escape;
}
fn start_csi(&mut self) {
self.clear_sequence();
self.state = State::CsiEntry;
}
fn start_string(&mut self, kind: StringKind) {
self.clear_sequence();
self.string_kind = Some(kind);
self.state = if kind == StringKind::Dcs {
State::DcsEntry
} else {
State::String
};
}
fn add_intermediate(&mut self, byte: u8) {
if self.intermediates.len() < self.options.max_intermediates {
self.intermediates.push(byte);
} else {
self.sequence_truncated = true;
}
}
fn add_private_marker(&mut self, byte: u8) {
if self.private_markers.len() < self.options.max_parameters {
self.private_markers.push(byte);
} else {
self.sequence_truncated = true;
}
}
fn add_parameter(&mut self, byte: u8) {
if self.sequence_truncated {
return;
}
if self.parameter_count == 0 {
self.parameter_count = 1;
}
if byte == b';' {
self.parameter_count = self.parameter_count.saturating_add(1);
self.parameter_bytes = 0;
} else {
if self.parameter_bytes >= MAX_PARAMETER_BYTES_PER_VALUE {
self.sequence_truncated = true;
return;
}
self.parameter_bytes += 1;
}
let byte_limit = self
.options
.max_parameters
.saturating_mul(MAX_PARAMETER_BYTES_PER_VALUE);
if self.parameter_count > self.options.max_parameters || self.parameters.len() >= byte_limit
{
self.sequence_truncated = true;
return;
}
self.parameters.push(byte);
}
fn append_string(&mut self, byte: u8) {
if self.string_data.len() < self.options.max_string_bytes {
self.string_data.push(byte);
} else {
self.string_truncated = true;
}
}
fn is_cancel(byte: u8) -> bool {
byte == 0x18 || byte == 0x1A
}
fn clear_sequence(&mut self) {
self.state = State::Ground;
self.utf8.reset();
self.intermediates.clear();
self.private_markers.clear();
self.parameters.clear();
self.parameter_count = 0;
self.parameter_bytes = 0;
self.sequence_truncated = false;
self.string_kind = None;
self.string_final = None;
self.string_data.clear();
self.string_truncated = false;
}
}
const fn is_private_marker(byte: u8) -> bool {
byte >= 0x3C && byte <= 0x3F
}