use std::cell::RefCell;
thread_local! {
static INPUT_REFUSAL: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn take_input_refusal() -> Option<String> {
INPUT_REFUSAL.with(|r| r.borrow_mut().take())
}
use std::io::{BufRead, Write};
#[derive(Default)]
pub struct Cursor {
buf: Vec<char>,
pos: usize,
done: bool,
}
impl Cursor {
fn text(s: &str) -> Cursor {
Cursor {
buf: s.chars().collect(),
pos: 0,
done: true,
}
}
fn at(&mut self, i: usize) -> Option<char> {
while i >= self.buf.len() {
if self.done || !self.fill() {
return None;
}
}
Some(self.buf[i])
}
fn fill(&mut self) -> bool {
let _ = std::io::stdout().flush();
let mut line = String::new();
match std::io::stdin().lock().read_line(&mut line) {
Ok(n) if n > 0 => match line.chars().find(|c| crate::jstr::is_reserved(*c as u32)) {
Some(c) => {
INPUT_REFUSAL
.with(|r| *r.borrow_mut() = Some(crate::jstr::reserved_message(c as u32)));
self.done = true;
false
}
None => {
self.buf.extend(line.chars());
true
}
},
_ => {
self.done = true;
false
}
}
}
fn line_from(&mut self, start: usize) -> Option<(String, usize)> {
self.at(start)?;
let mut out = String::new();
let mut i = start;
while let Some(c) = self.at(i) {
i += 1;
match c {
'\n' | '\u{2028}' | '\u{2029}' | '\u{85}' => return Some((out, i)),
'\r' => {
if self.at(i) == Some('\n') {
i += 1;
}
return Some((out, i));
}
_ => out.push(c),
}
}
Some((out, i))
}
fn token_from(&mut self, start: usize) -> Option<(String, usize)> {
let mut i = start;
while is_java_whitespace(self.at(i)?) {
i += 1;
}
let mut tok = String::new();
while let Some(c) = self.at(i) {
if is_java_whitespace(c) {
break;
}
tok.push(c);
i += 1;
}
Some((tok, i))
}
}
thread_local! {
static STDIN: RefCell<Cursor> = RefCell::new(Cursor::default());
}
pub fn set_stdin_text(input: Option<&str>) -> Result<(), String> {
if let Some(c) = input.and_then(|s| s.chars().find(|c| crate::jstr::is_reserved(*c as u32))) {
return Err(crate::jstr::reserved_message(c as u32));
}
STDIN.with(|s| *s.borrow_mut() = input.map(Cursor::text).unwrap_or_default());
Ok(())
}
fn is_java_whitespace(c: char) -> bool {
match c {
'\u{a0}' | '\u{2007}' | '\u{202f}' => false,
'\u{1c}'..='\u{1f}' => true,
_ => c.is_whitespace() && c != '\u{85}',
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
InputStream,
InputStreamReader,
StringReader,
BufferedReader,
Scanner,
}
impl Kind {
pub fn class_name(self) -> &'static str {
match self {
Kind::InputStream => "java.io.BufferedInputStream",
Kind::InputStreamReader => "java.io.InputStreamReader",
Kind::StringReader => "java.io.StringReader",
Kind::BufferedReader => "java.io.BufferedReader",
Kind::Scanner => "java.util.Scanner",
}
}
}
pub struct Reader {
pub kind: Kind,
own: Option<Cursor>,
closed: bool,
}
pub enum Out {
Str(String),
Int(i64),
Float(f64),
Bool(bool),
Null,
Unit,
Lines(Vec<String>),
}
pub type Fail = (&'static str, Option<String>);
impl Reader {
pub fn stdin(kind: Kind) -> Reader {
Reader {
kind,
own: None,
closed: false,
}
}
pub fn text(kind: Kind, s: &str) -> Reader {
Reader {
kind,
own: Some(Cursor::text(s)),
closed: false,
}
}
pub fn wrap(kind: Kind, inner: &mut Reader) -> Reader {
Reader {
kind,
own: inner
.own
.as_mut()
.map(|c| std::mem::replace(c, Cursor::text(""))),
closed: false,
}
}
fn with<R>(&mut self, f: impl FnOnce(&mut Cursor) -> R) -> R {
match &mut self.own {
Some(c) => f(c),
None => STDIN.with(|s| {
let mut c = s.borrow_mut();
if c.pos > 1 << 16 {
let pos = c.pos;
c.buf.drain(..pos);
c.pos = 0;
}
f(&mut c)
}),
}
}
pub fn call(&mut self, method: &str, args: &[ArgVal]) -> Option<Result<Out, Fail>> {
match self.kind {
Kind::Scanner => self.scanner(method, args),
Kind::BufferedReader
| Kind::InputStreamReader
| Kind::StringReader
| Kind::InputStream => self.reader(method, args),
}
}
fn scanner(&mut self, method: &str, args: &[ArgVal]) -> Option<Result<Out, Fail>> {
if method == "close" && args.is_empty() {
self.closed = true;
return Some(Ok(Out::Unit));
}
if self.closed {
return Some(Err((
"IllegalStateException",
Some("Scanner closed".into()),
)));
}
if !args.is_empty() {
return None;
}
let no_elem: Fail = ("NoSuchElementException", None);
Some(match method {
"hasNext" => Ok(Out::Bool(self.with(|c| c.token_from(c.pos).is_some()))),
"hasNextLine" => Ok(Out::Bool(self.with(|c| c.at(c.pos).is_some()))),
"next" => self.with(|c| match c.token_from(c.pos) {
Some((t, end)) => {
c.pos = end;
Ok(Out::Str(t))
}
None => Err(no_elem),
}),
"nextLine" => self.with(|c| match c.line_from(c.pos) {
Some((l, end)) => {
c.pos = end;
Ok(Out::Str(l))
}
None => Err(("NoSuchElementException", Some("No line found".into()))),
}),
"hasNextInt" | "hasNextLong" | "hasNextShort" | "hasNextByte" | "hasNextDouble"
| "hasNextFloat" | "hasNextBoolean" => {
let want = &method["hasNext".len()..];
Ok(Out::Bool(self.with(|c| {
c.token_from(c.pos)
.is_some_and(|(t, _)| parse_token(want, &t).is_ok())
})))
}
"nextInt" | "nextLong" | "nextShort" | "nextByte" | "nextDouble" | "nextFloat"
| "nextBoolean" => {
let want = &method["next".len()..];
self.with(|c| match c.token_from(c.pos) {
None => Err(no_elem),
Some((t, end)) => {
let v =
parse_token(want, &t).map_err(|msg| ("InputMismatchException", msg))?;
c.pos = end;
Ok(v)
}
})
}
_ => return None,
})
}
fn reader(&mut self, method: &str, args: &[ArgVal]) -> Option<Result<Out, Fail>> {
if method == "close" && args.is_empty() {
self.closed = true;
return Some(Ok(Out::Unit));
}
if self.closed {
return Some(Err(("IOException", Some("Stream closed".into()))));
}
let line_reader = self.kind == Kind::BufferedReader;
Some(match (method, args) {
("readLine", []) if line_reader => Ok(self.with(|c| match c.line_from(c.pos) {
Some((l, end)) => {
c.pos = end;
Out::Str(l)
}
None => Out::Null,
})),
("lines", []) if line_reader => Ok(Out::Lines(self.with(|c| {
let mut out = Vec::new();
while let Some((l, end)) = c.line_from(c.pos) {
c.pos = end;
out.push(l);
}
out
}))),
("read", []) => Ok(Out::Int(self.with(|c| match c.at(c.pos) {
Some(ch) => {
c.pos += 1;
ch as i64
}
None => -1,
}))),
("ready", []) => Ok(Out::Bool(self.with(|c| c.done || c.pos < c.buf.len()))),
("skip", [ArgVal::Int(n)]) => Ok(Out::Int(self.with(|c| {
let mut k = 0;
while k < *n && c.at(c.pos).is_some() {
c.pos += 1;
k += 1;
}
k
}))),
_ => return None,
})
}
}
pub enum ArgVal {
Int(i64),
Str(String),
}
fn parse_token(want: &str, t: &str) -> Result<Out, Option<String>> {
match want {
"Boolean" => match t.to_ascii_lowercase().as_str() {
"true" => Ok(Out::Bool(true)),
"false" => Ok(Out::Bool(false)),
_ => Err(None),
},
"Double" | "Float" => parse_decimal(t)
.map(|v| Out::Float(if want == "Float" { v as f32 as f64 } else { v }))
.ok_or(None),
_ => {
let digits = integer_digits(t).ok_or(None)?;
let (lo, hi) = match want {
"Int" => (i32::MIN as i64, i32::MAX as i64),
"Short" => (i16::MIN as i64, i16::MAX as i64),
"Byte" => (i8::MIN as i64, i8::MAX as i64),
_ => (i64::MIN, i64::MAX),
};
match digits.parse::<i64>() {
Ok(v) if (lo..=hi).contains(&v) => Ok(Out::Int(v)),
_ => Err(Some(format!("For input string: \"{digits}\""))),
}
}
}
}
fn integer_digits(t: &str) -> Option<String> {
let (neg, body) = match t.as_bytes().first()? {
b'-' => (true, &t[1..]),
b'+' => (false, &t[1..]),
_ => (false, t),
};
if body.is_empty() || !body.bytes().all(|b| b.is_ascii_digit() || b == b',') {
return None;
}
if body.contains(',') {
let groups: Vec<&str> = body.split(',').collect();
let first = groups[0];
if first.is_empty() || first.len() > 3 || first.starts_with('0') {
return None;
}
if groups[1..].iter().any(|g| g.len() != 3) {
return None;
}
}
let digits: String = body.chars().filter(|c| *c != ',').collect();
Some(if neg { format!("-{digits}") } else { digits })
}
fn parse_decimal(t: &str) -> Option<f64> {
let (neg, body) = match t.as_bytes().first()? {
b'-' => (true, &t[1..]),
b'+' => (false, &t[1..]),
_ => (false, t),
};
let v = match body {
"NaN" => f64::NAN,
"Infinity" => f64::INFINITY,
_ => {
let (mantissa, exp) = match body.find(['e', 'E']) {
Some(i) => (&body[..i], Some(&body[i + 1..])),
None => (body, None),
};
if let Some(e) = exp {
let e = e.strip_prefix(['+', '-']).unwrap_or(e);
if e.is_empty() || !e.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
}
let (int, frac) = match mantissa.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (mantissa, None),
};
if !frac.is_none_or(|f| f.bytes().all(|b| b.is_ascii_digit())) {
return None;
}
if int.is_empty() && frac.is_none_or(str::is_empty) {
return None;
}
let int = if int.is_empty() {
String::new()
} else {
integer_digits(int).filter(|d| !d.starts_with('-'))?
};
let plain = format!(
"{int}{}{}",
frac.map(|f| format!(".{f}")).unwrap_or_default(),
exp.map(|e| format!("e{e}")).unwrap_or_default()
);
plain.parse::<f64>().ok()?
}
};
Some(if neg { -v } else { v })
}
pub struct Tokenizer {
tokens: Vec<String>,
next: usize,
}
impl Tokenizer {
pub fn new(s: &str, delims: Option<&str>, return_delims: bool) -> Tokenizer {
let delims: Vec<char> = delims.unwrap_or(" \t\n\r\x0c").chars().collect();
let mut tokens = Vec::new();
let mut cur = String::new();
for c in s.chars() {
if delims.contains(&c) {
if !cur.is_empty() {
tokens.push(std::mem::take(&mut cur));
}
if return_delims {
tokens.push(c.to_string());
}
} else {
cur.push(c);
}
}
if !cur.is_empty() {
tokens.push(cur);
}
Tokenizer { tokens, next: 0 }
}
pub fn call(&mut self, method: &str, argc: usize) -> Option<Result<Out, Fail>> {
Some(match (method, argc) {
("hasMoreTokens" | "hasMoreElements", 0) => {
Ok(Out::Bool(self.next < self.tokens.len()))
}
("countTokens", 0) => Ok(Out::Int((self.tokens.len() - self.next) as i64)),
("nextToken" | "nextElement", 0) => match self.tokens.get(self.next) {
Some(t) => {
self.next += 1;
Ok(Out::Str(t.clone()))
}
None => Err(("NoSuchElementException", None)),
},
_ => return None,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum WKind {
PrintStream,
PrintWriter,
BufferedWriter,
OutputStreamWriter,
BufferedOutputStream,
StringWriter,
}
impl WKind {
pub fn class_name(self) -> &'static str {
match self {
WKind::PrintStream => "java.io.PrintStream",
WKind::PrintWriter => "java.io.PrintWriter",
WKind::BufferedWriter => "java.io.BufferedWriter",
WKind::OutputStreamWriter => "java.io.OutputStreamWriter",
WKind::BufferedOutputStream => "java.io.BufferedOutputStream",
WKind::StringWriter => "java.io.StringWriter",
}
}
pub fn is_print(self) -> bool {
matches!(self, WKind::PrintStream | WKind::PrintWriter)
}
pub fn is_stream(self) -> bool {
matches!(self, WKind::PrintStream | WKind::BufferedOutputStream)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Sink {
Stdout,
Stderr,
Handle(u32),
Own,
Buffer(u32),
}
const OUT_BUF: usize = 8192;
pub struct Writer {
pub kind: WKind,
pub sink: Sink,
pub buf: String,
held: usize,
pub autoflush: bool,
pub closed: bool,
pub error: bool,
}
impl Writer {
pub fn new(kind: WKind, sink: Sink, autoflush: bool) -> Writer {
Writer {
kind,
sink,
buf: String::new(),
held: 0,
autoflush,
closed: false,
error: false,
}
}
pub fn accept(&mut self, text: &str) -> Result<Vec<String>, Fail> {
if self.closed && self.kind != WKind::StringWriter {
if self.kind.is_print() {
self.error = true;
return Ok(Vec::new());
}
return Err(("IOException", Some("Stream closed".to_string())));
}
let mut out = Vec::new();
match self.kind {
WKind::PrintStream | WKind::PrintWriter => out.push(text.to_string()),
WKind::StringWriter => match self.sink {
Sink::Buffer(_) => out.push(text.to_string()),
_ => self.buf.push_str(text),
},
WKind::BufferedWriter => {
for c in text.chars() {
self.buf.push(c);
self.held += 1;
if self.held >= OUT_BUF {
out.push(std::mem::take(&mut self.buf));
self.held = 0;
}
}
}
WKind::OutputStreamWriter => {
for c in text.chars() {
if self.buf.len() + c.len_utf8() > OUT_BUF {
out.push(std::mem::take(&mut self.buf));
}
self.buf.push(c);
}
}
WKind::BufferedOutputStream => {
if text.len() >= OUT_BUF {
if !self.buf.is_empty() {
out.push(std::mem::take(&mut self.buf));
}
out.push(text.to_string());
} else {
if text.len() > OUT_BUF - self.buf.len() {
out.push(std::mem::take(&mut self.buf));
}
self.buf.push_str(text);
}
}
}
Ok(out)
}
pub fn drain(&mut self) -> Result<String, Fail> {
if self.closed && self.kind != WKind::StringWriter {
if self.kind.is_print() {
self.error = true;
return Ok(String::new());
}
return Err(("IOException", Some("Stream closed".to_string())));
}
if self.kind == WKind::StringWriter {
return Ok(String::new());
}
self.held = 0;
Ok(std::mem::take(&mut self.buf))
}
}