use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use crate::classes::buffer;
use crate::classes::enumerator;
use crate::classes::object_with;
use crate::runtime::{
Object, Runtime, RuntimeError, RuntimeFailure, SharedCell, TypeName, Value, expected_number, expected_type,
put,
};
const STATE: &str = "file state";
const STATE_CLASS: &str = "file-state";
const PROPERTIES: [&str; 5] = ["pos", "length", "ateof", "encoding", "handle"];
const METHODS: [&str; 35] = [
"read",
"readline",
"readchar",
"readuchar",
"readshort",
"readushort",
"readint",
"readuint",
"readint64",
"readfloat",
"readdouble",
"write",
"writeline",
"writechar",
"writeuchar",
"writeshort",
"writeushort",
"writeint",
"writeuint",
"writeint64",
"writefloat",
"writedouble",
"rawread",
"rawwrite",
"seek",
"close",
"ownprops",
"hasownprop",
"defineprop",
"deleteprop",
"getownpropdesc",
"hasprop",
"hasmethod",
"getmethod",
"hasbase",
];
const CLOSED: i64 = -1;
const CONSOLE: i64 = -2;
const CHUNK: i64 = 4096;
struct File {
handle: i64,
pos: i64,
encoding: Encoding,
mode: String,
}
impl File {
fn can_read(&self) -> bool {
self.mode.contains('r')
}
fn can_write(&self) -> bool {
self.mode.contains('w') || self.mode.contains('a')
}
}
#[derive(Clone, Copy)]
pub(crate) enum Encoding {
Cp1252,
Cp1250,
CodePage(u32),
Utf8 { raw: bool },
Utf16 { raw: bool },
}
pub(crate) fn names() -> Vec<&'static str> {
PROPERTIES.iter().chain(METHODS.iter()).copied().collect()
}
pub(crate) fn open_file(
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let file = open(arguments, rt, line)?;
Ok(object_with("file", vec![(STATE, stored(&file))]))
}
pub(crate) fn call(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let method = method.to_lowercase();
if rt
.dialect()
.carries_the_member_of_the_extension("file", &method)
{
if method == "flush" {
return Some(Ok(Value::Text(String::new())));
}
return None;
}
match method.as_str() {
"read" => Some(read_text(this, arguments, rt, line)),
"readline" => Some(read_line(this, rt, line)),
"readchar" => Some(read_number(rt, this, 1, line, |bytes| {
Value::Int(bytes[0] as i8 as i64)
})),
"readuchar" => Some(read_number(rt, this, 1, line, |bytes| {
Value::Int(bytes[0] as i64)
})),
"readshort" => Some(read_number(rt, this, 2, line, |bytes| {
Value::Int(little(bytes) as u16 as i16 as i64)
})),
"readushort" => Some(read_number(rt, this, 2, line, |bytes| {
Value::Int(little(bytes) as u16 as i64)
})),
"readint" => Some(read_number(rt, this, 4, line, |bytes| {
Value::Int(little(bytes) as u32 as i32 as i64)
})),
"readuint" => Some(read_number(rt, this, 4, line, |bytes| {
Value::Int(little(bytes) as u32 as i64)
})),
"readint64" => Some(read_number(rt, this, 8, line, |bytes| {
Value::Int(little(bytes) as i64)
})),
"readfloat" => Some(read_number(rt, this, 4, line, |bytes| {
Value::Float(f32::from_bits(little(bytes) as u32) as f64)
})),
"readdouble" => Some(read_number(rt, this, 8, line, |bytes| {
Value::Float(f64::from_bits(little(bytes)))
})),
"write" => Some(write_text(this, arguments, rt, line)),
"writeline" => Some(write_line(this, arguments, rt, line)),
"writechar" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFF, 1)
})),
"writeuchar" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFF, 1)
})),
"writeshort" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFFFF, 2)
})),
"writeushort" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFFFF, 2)
})),
"writeint" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFFFF_FFFF, 4)
})),
"writeuint" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64 & 0xFFFF_FFFF, 4)
})),
"writeint64" => Some(write_number(rt, this, arguments, line, |value| {
little_bytes(value as i64 as u64, 8)
})),
"writefloat" => Some(write_number(rt, this, arguments, line, |value| {
float_bytes(value, true)
})),
"writedouble" => Some(write_number(rt, this, arguments, line, |value| {
float_bytes(value, false)
})),
"rawread" => Some(raw_read(this, arguments, rt, line)),
"rawwrite" => Some(raw_write(this, arguments, rt, line)),
"seek" => Some(seek(this, arguments, rt, line)),
"close" => Some(close(this, rt, line)),
_ => base_method(&method, this, arguments, rt, line),
}
}
pub(crate) fn property(
name: &str,
this: &Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
match name.to_lowercase().as_str() {
"pos" => Some(state(this, line).map(|file| {
Value::Int(if is_closed(&file) { -1 } else { file.pos })
})),
"length" => Some(length(rt, this, line)),
"ateof" => Some(at_eof(rt, this, line)),
"encoding" => {
Some(state(this, line).map(|file| Value::Text(file.encoding.name())))
}
"handle" => Some(state(this, line).map(|file| Value::Int(file.handle))),
_ => None,
}
}
pub(crate) fn set_property(
name: &str,
this: &Value,
value: Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<(), RuntimeFailure>> {
match name.to_lowercase().as_str() {
"pos" => Some(set_pos(this, value, line)),
"length" => Some(set_length(rt, this, value, line)),
"encoding" => Some(set_encoding(this, value, line)),
_ => None,
}
}
pub(crate) fn item(
_key: &Value,
_this: &Value,
_rt: &mut Runtime,
_line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
None
}
fn fail(message: impl Into<String>, line: u32) -> RuntimeFailure {
let message = message.into();
RuntimeFailure::Error(RuntimeError {
message: the_reason_of_the_machine(&message),
line,
})
}
fn the_reason_of_the_machine(reason: &str) -> String {
let Some(without_the_bracket) = reason.strip_suffix(')') else {
return reason.to_string();
};
let Some((message, number)) = without_the_bracket.rsplit_once(" (os error ") else {
return reason.to_string();
};
match number.parse::<i64>() {
Ok(number) => format!("({number}) {message}"),
Err(_) => reason.to_string(),
}
}
fn whole(value: &Value, line: u32) -> Result<i64, RuntimeFailure> {
match value {
Value::Int(number) => Ok(*number),
Value::Float(number) => Ok(*number as i64),
other => Err(fail(
expected_type(TypeName::Integer, other.type_name()),
line,
)),
}
}
fn number(value: &Value, line: u32) -> Result<f64, RuntimeFailure> {
value
.to_number_strict()
.map_err(|_| fail(expected_number(value), line))
}
fn state(this: &Value, line: u32) -> Result<File, RuntimeFailure> {
let Value::Object(object) = this else {
return Err(fail("this value is not a file.", line));
};
let inner = match object.borrow().value_of(STATE) {
Some(Value::Object(inner)) => inner.clone(),
_ => return Err(fail("this value is not a file.", line)),
};
let inner = inner.borrow();
let handle = inner
.value_of("handle")
.and_then(|value| value.to_number())
.unwrap_or(CLOSED as f64) as i64;
let pos = inner
.value_of("pos")
.and_then(|value| value.to_number())
.unwrap_or(0.0) as i64;
let mode = inner
.value_of("mode")
.map(|value| value.to_text())
.unwrap_or_else(|| "rw".to_string());
let encoding = match inner.value_of("encoding") {
Some(value) => Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?,
None => Encoding::of(crate::files::encoding()).map_err(|reason| fail(reason, line))?,
};
Ok(File {
handle,
pos,
encoding,
mode,
})
}
fn stored(file: &File) -> Value {
object_with(
STATE_CLASS,
vec![
("handle", Value::Int(file.handle)),
("pos", Value::Int(file.pos)),
("encoding", Value::Text(file.encoding.name())),
("mode", Value::Text(file.mode.clone())),
],
)
}
fn restore(this: &Value, file: &File) {
let Value::Object(object) = this else { return };
put(&mut object.borrow_mut().properties, STATE, stored(file));
}
fn is_closed(file: &File) -> bool {
file.handle == CLOSED
}
fn is_console(file: &File) -> bool {
file.handle == CONSOLE
}
fn write_to_the_console(rt: &mut Runtime, bytes: &[u8], encoding: Encoding) {
let text = match decode(bytes, encoding) {
Ok((text, _)) => text,
Err(_) => String::new(),
};
rt.push_output(text);
}
fn read_at(
rt: &mut Runtime,
handle: i64,
pos: i64,
count: i64,
line: u32,
) -> Result<Vec<u8>, RuntimeFailure> {
rt.desktop()
.read_file_at(handle, pos, count)
.map_err(|reason| fail(reason, line))
}
fn open(arguments: &[Value], rt: &mut Runtime, line: u32) -> Result<File, RuntimeFailure> {
let path = match arguments.first() {
Some(value) => value.to_text(),
None => return Err(fail("the file needs a path.", line)),
};
let mode = match arguments.get(1) {
Some(value) => value.to_text(),
None => "r".to_string(),
};
let kind = mode.to_lowercase();
if !matches!(kind.as_str(), "r" | "w" | "a" | "rw") {
return Err(fail("Invalid parameter(s).", line));
}
let encoding = match arguments.get(2) {
Some(value) => Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?,
None => Encoding::of(crate::files::encoding()).map_err(|reason| fail(reason, line))?,
};
if path == "*" {
return Ok(File {
handle: CONSOLE,
pos: 0,
encoding,
mode,
});
}
let handle = rt
.desktop()
.open_file(&path, &mode)
.map_err(|reason| fail(reason, line))?;
let pos = if mode.contains('a') {
rt.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?
} else {
0
};
let mut file = File {
handle,
pos,
encoding,
mode,
};
if kind.contains('r') || kind == "a" {
if let Ok(bytes) = read_at(rt, handle, 0, 3, line) {
if let Some((encoding, at)) = Encoding::detect(&bytes) {
file.encoding = encoding;
if file.pos == 0 {
file.pos = at as i64;
}
}
}
}
if (kind == "w" || kind == "a") && file.pos == 0 {
if let Some(mark) = file.encoding.mark() {
write_bytes(rt, &mut file, &mark, line)?;
}
}
Ok(file)
}
fn read_text(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
let count = match arguments.first() {
Some(value) => Some(whole(value, line)?),
None => None,
};
let text = read_chars(rt, &mut file, count, line)?;
restore(this, &file);
Ok(Value::Text(text))
}
fn read_chars(
rt: &mut Runtime,
file: &mut File,
count: Option<i64>,
line: u32,
) -> Result<String, RuntimeFailure> {
if is_closed(file) || is_console(file) || !file.can_read() {
return Ok(String::new());
}
let handle = file.handle;
let (text, used) = match count {
Some(count) => {
if count < 0 {
return Err(fail("the count of characters cannot be negative.", line));
}
let wide = match file.encoding {
Encoding::Cp1252 | Encoding::Cp1250 | Encoding::CodePage(_) => count,
Encoding::Utf8 { .. } => count * 4,
Encoding::Utf16 { .. } => count * 2,
};
let bytes = read_at(rt, handle, file.pos, wide, line)?;
let (text, used) =
decode(&bytes, file.encoding).map_err(|reason| fail(reason, line))?;
match file.encoding {
Encoding::Utf8 { .. } => {
let (text, used) = take(&text, count as usize);
(text, used)
}
Encoding::Cp1252 | Encoding::Cp1250 | Encoding::CodePage(_) => {
let (text, used) = take(&text, count as usize);
(text, used)
}
Encoding::Utf16 { .. } => (text, used),
}
}
None => {
let size = rt
.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?;
let bytes = read_at(rt, handle, file.pos, (size - file.pos).max(0), line)?;
decode(&bytes, file.encoding).map_err(|reason| fail(reason, line))?
}
};
file.pos += used as i64;
Ok(text)
}
fn read_line(this: &Value, rt: &mut Runtime, line: u32) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
if is_closed(&file) || is_console(&file) || !file.can_read() {
return Ok(Value::Text(String::new()));
}
let handle = file.handle;
let mut raw: Vec<u8> = Vec::new();
let text = loop {
let bytes = read_at(rt, handle, file.pos + raw.len() as i64, CHUNK, line)?;
let at_end = bytes.is_empty();
raw.extend_from_slice(&bytes);
match line_of(&raw, file.encoding) {
Some((end, after)) => {
let (text, _) =
decode(&raw[..end], file.encoding).map_err(|reason| fail(reason, line))?;
file.pos += after as i64;
break text;
}
None if at_end => {
let (text, used) =
decode(&raw, file.encoding).map_err(|reason| fail(reason, line))?;
file.pos += used as i64;
break text;
}
None => {}
}
};
restore(this, &file);
Ok(Value::Text(text))
}
fn read_number(
rt: &mut Runtime,
this: &Value,
count: usize,
line: u32,
of: fn(&[u8]) -> Value,
) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
if is_closed(&file) || is_console(&file) || !file.can_read() {
return Ok(Value::Text(String::new()));
}
let handle = file.handle;
let bytes = read_at(rt, handle, file.pos, count as i64, line)?;
if bytes.is_empty() {
return Err(fail("the read is past the end of the file.", line));
}
let mut full = bytes.clone();
full.resize(count, 0);
file.pos += bytes.len() as i64;
restore(this, &file);
Ok(of(&full))
}
fn write_text(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let text = match arguments.first() {
Some(value) => value.to_text(),
None => return Err(fail("Too few parameters passed to function.", line)),
};
let mut file = state(this, line)?;
let written = text.chars().count() as i64;
if !is_closed(&file) && file.can_write() {
if is_console(&file) {
rt.push_output(text);
file.pos += written;
} else {
let bytes = encode(&text, file.encoding);
write_bytes(rt, &mut file, &bytes, line)?;
}
restore(this, &file);
}
Ok(Value::Int(written))
}
fn write_line(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let text = match arguments.first() {
Some(value) => value.to_text(),
None => String::new(),
};
let mut file = state(this, line)?;
let written = text.chars().count() as i64 + 1;
if !is_closed(&file) && file.can_write() {
if is_console(&file) {
let mut line_of_text = text;
line_of_text.push('\n');
rt.push_output(line_of_text);
file.pos += written;
} else {
let mut bytes = encode(&text, file.encoding);
bytes.extend_from_slice(&encode("\n", file.encoding));
write_bytes(rt, &mut file, &bytes, line)?;
}
restore(this, &file);
}
Ok(Value::Int(written))
}
fn write_number(
rt: &mut Runtime,
this: &Value,
arguments: &[Value],
line: u32,
of: fn(f64) -> Vec<u8>,
) -> Result<Value, RuntimeFailure> {
let value = match arguments.first() {
Some(value) => number(value, line)?,
None => return Err(fail("Too few parameters passed to function.", line)),
};
let mut file = state(this, line)?;
let bytes = of(value);
let written = bytes.len() as i64;
if !is_closed(&file) && file.can_write() {
if is_console(&file) {
write_to_the_console(rt, &bytes, file.encoding);
file.pos += written;
} else {
write_bytes(rt, &mut file, &bytes, line)?;
}
restore(this, &file);
}
Ok(Value::Int(written))
}
fn write_bytes(
rt: &mut Runtime,
file: &mut File,
bytes: &[u8],
line: u32,
) -> Result<Value, RuntimeFailure> {
let handle = file.handle;
let written = rt
.desktop()
.write_file_at(handle, file.pos, bytes)
.map_err(|reason| fail(reason, line))?;
file.pos += written as i64;
Ok(Value::Int(written as i64))
}
fn raw_read(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
if is_closed(&file) || !file.can_read() {
return Ok(Value::Int(0));
}
let handle = file.handle;
let target = match arguments.first() {
Some(value) => value.clone(),
None => return Err(fail("Too few parameters passed to function.", line)),
};
let count = match arguments.get(1) {
Some(value) => whole(value, line)?,
None => buffer::size_of(&target, line)?,
};
if count < 0 {
return Err(fail("the count of bytes cannot be negative.", line));
}
let bytes = read_at(rt, handle, file.pos, count, line)?;
let written = buffer::fill(&target, &bytes, line)?;
file.pos += bytes.len() as i64;
restore(this, &file);
Ok(Value::Int(written as i64))
}
fn raw_write(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
let bytes = match arguments.first() {
Some(Value::Object(_)) => buffer::raw_bytes(&arguments[0], line)?,
Some(Value::Text(text)) => encode(text, Encoding::Utf16 { raw: false }),
Some(other) => {
return Err(fail(
expected_type(TypeName::Object, other.type_name()),
line,
));
}
None => return Err(fail("Too few parameters passed to function.", line)),
};
let count = match arguments.get(1) {
Some(value) => whole(value, line)?,
None => bytes.len() as i64,
};
if count < 0 || count as usize > bytes.len() {
return Err(fail("there are not that many bytes to write.", line));
}
let written = count;
if !is_closed(&file) && file.can_write() {
if is_console(&file) {
write_to_the_console(rt, &bytes[..count as usize], file.encoding);
file.pos += written;
} else {
write_bytes(rt, &mut file, &bytes[..count as usize], line)?;
}
restore(this, &file);
}
Ok(Value::Int(written))
}
fn seek(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let distance = match arguments.first() {
Some(value) => whole(value, line)?,
None => return Err(fail("Too few parameters passed to function.", line)),
};
let mut file = state(this, line)?;
if is_closed(&file) || is_console(&file) {
return Ok(Value::Int(0));
}
let handle = file.handle;
let origin = match arguments.get(1) {
Some(value) => whole(value, line)?,
None => {
if distance < 0 {
2
} else {
0
}
}
};
let target = match origin {
0 => distance,
1 => file.pos + distance,
2 => {
let size = rt
.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?;
size + distance
}
_ => return Ok(Value::Int(0)),
};
if target < 0 {
return Ok(Value::Int(0));
}
file.pos = target;
restore(this, &file);
Ok(Value::Int(1))
}
fn close(this: &Value, rt: &mut Runtime, line: u32) -> Result<Value, RuntimeFailure> {
let mut file = state(this, line)?;
if file.handle == CONSOLE {
return Ok(Value::Text(String::new()));
}
if file.handle >= 0 {
rt.desktop()
.close_file(file.handle)
.map_err(|reason| fail(reason, line))?;
file.handle = CLOSED;
restore(this, &file);
}
Ok(Value::Text(String::new()))
}
fn length(rt: &mut Runtime, this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
let file = state(this, line)?;
if is_closed(&file) {
return Ok(Value::Int(0));
}
if is_console(&file) {
return Ok(Value::Int(file.pos));
}
let handle = file.handle;
let size = rt
.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?;
Ok(Value::Int(size))
}
fn at_eof(rt: &mut Runtime, this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
let file = state(this, line)?;
if is_closed(&file) || is_console(&file) {
return Ok(Value::Int(1));
}
let handle = file.handle;
let size = rt
.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?;
Ok(Value::Int(if file.pos >= size { 1 } else { 0 }))
}
fn set_pos(this: &Value, value: Value, line: u32) -> Result<(), RuntimeFailure> {
let pos = whole(&value, line)?;
if pos < 0 {
return Err(fail("the position of a file cannot be negative.", line));
}
let mut file = state(this, line)?;
if is_closed(&file) {
return Ok(());
}
file.pos = pos;
restore(this, &file);
Ok(())
}
fn set_length(
rt: &mut Runtime,
this: &Value,
value: Value,
line: u32,
) -> Result<(), RuntimeFailure> {
let size = whole(&value, line)?;
if size < 0 {
return Err(fail("the length of a file cannot be negative.", line));
}
let file = state(this, line)?;
if is_closed(&file) {
return Ok(());
}
let handle = file.handle;
let current = rt
.desktop()
.file_size(handle)
.map_err(|reason| fail(reason, line))?;
if size < current {
return Err(fail(
"this desktop cannot make a file shorter: it cannot cut one.",
line,
));
}
if size > current {
let zeros = vec![0u8; (size - current) as usize];
rt.desktop()
.write_file_at(handle, current, &zeros)
.map_err(|reason| fail(reason, line))?;
}
Ok(())
}
fn set_encoding(this: &Value, value: Value, line: u32) -> Result<(), RuntimeFailure> {
let encoding = Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?;
let mut file = state(this, line)?;
file.encoding = encoding;
restore(this, &file);
Ok(())
}
impl Encoding {
pub(crate) fn of(name: &str) -> Result<Encoding, String> {
let name = name.trim().to_uppercase();
let (name, raw) = match name.strip_suffix("-RAW") {
Some(short) => (short, true),
None => (name.as_str(), false),
};
match name {
"UTF-8" | "UTF8" => Ok(Encoding::Utf8 { raw }),
"UTF-16" | "UTF16" => Ok(Encoding::Utf16 { raw }),
"CP0" | "CP1252" => Ok(Encoding::Cp1252),
"CP1250" => Ok(Encoding::Cp1250),
other => {
let number = other
.strip_prefix("CP")
.or_else(|| other.strip_prefix("WINDOWS-"));
match number.and_then(|digits| digits.parse::<u32>().ok()) {
Some(page) if page > 0 && page != 1252 && page != 1250 => {
Ok(Encoding::CodePage(page))
}
Some(1252) => Ok(Encoding::Cp1252),
Some(1250) => Ok(Encoding::Cp1250),
_ => Err(format!(
"the encoding {other:?} is not one this runtime carries: it knows the code page of the machine (CP1252), UTF-8 and UTF-16."
)),
}
}
}
}
fn name(self) -> String {
match self {
Encoding::Cp1252 => "CP1252".to_string(),
Encoding::Cp1250 => "CP1250".to_string(),
Encoding::CodePage(page) => format!("CP{page}"),
Encoding::Utf8 { .. } => "UTF-8".to_string(),
Encoding::Utf16 { .. } => "UTF-16".to_string(),
}
}
pub(crate) fn mark(self) -> Option<Vec<u8>> {
match self {
Encoding::Cp1252 | Encoding::Cp1250 | Encoding::CodePage(_) => None,
Encoding::Utf8 { raw } => {
if raw {
None
} else {
Some(vec![0xEF, 0xBB, 0xBF])
}
}
Encoding::Utf16 { raw } => {
if raw {
None
} else {
Some(vec![0xFF, 0xFE])
}
}
}
}
pub(crate) fn detect(bytes: &[u8]) -> Option<(Encoding, usize)> {
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return Some((Encoding::Utf8 { raw: false }, 3));
}
if bytes.starts_with(&[0xFF, 0xFE]) {
return Some((Encoding::Utf16 { raw: false }, 2));
}
None
}
}
const CP1252: [(u8, char); 27] = [
(0x80, '\u{20AC}'),
(0x82, '\u{201A}'),
(0x83, '\u{0192}'),
(0x84, '\u{201E}'),
(0x85, '\u{2026}'),
(0x86, '\u{2020}'),
(0x87, '\u{2021}'),
(0x88, '\u{02C6}'),
(0x89, '\u{2030}'),
(0x8A, '\u{0160}'),
(0x8B, '\u{2039}'),
(0x8C, '\u{0152}'),
(0x8E, '\u{017D}'),
(0x91, '\u{2018}'),
(0x92, '\u{2019}'),
(0x93, '\u{201C}'),
(0x94, '\u{201D}'),
(0x95, '\u{2022}'),
(0x96, '\u{2013}'),
(0x97, '\u{2014}'),
(0x98, '\u{02DC}'),
(0x99, '\u{2122}'),
(0x9A, '\u{0161}'),
(0x9B, '\u{203A}'),
(0x9C, '\u{0153}'),
(0x9E, '\u{017E}'),
(0x9F, '\u{0178}'),
];
fn encode_cp1252(text: &str) -> Vec<u8> {
let mut bytes = Vec::new();
for character in text.chars() {
match the_byte_of_cp1252(character) {
Some(byte) => bytes.push(byte),
None => bytes.push(b'?'),
}
}
bytes
}
fn the_byte_of_cp1252(character: char) -> Option<u8> {
let code = character as u32;
if code < 0x80 || (0xA0..=0xFF).contains(&code) {
return Some(code as u8);
}
CP1252
.iter()
.find(|(_, other)| *other == character)
.map(|(byte, _)| *byte)
}
fn decode_cp1252(bytes: &[u8]) -> (String, usize) {
let mut text = String::new();
for byte in bytes {
text.push(the_character_of_cp1252(*byte));
}
(text, bytes.len())
}
fn the_character_of_cp1252(byte: u8) -> char {
match byte {
0x80..=0x9F => match CP1252.iter().find(|(code, _)| *code == byte) {
Some((_, character)) => *character,
None => '\u{FFFD}',
},
other => other as char,
}
}
const CP1250: [char; 128] = [
'\u{20AC}', '\u{FFFD}', '\u{201A}', '\u{FFFD}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}',
'\u{FFFD}', '\u{2030}', '\u{0160}', '\u{2039}', '\u{015A}', '\u{0164}', '\u{017D}', '\u{0179}',
'\u{FFFD}', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}',
'\u{FFFD}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{015B}', '\u{0165}', '\u{017E}', '\u{017A}',
'\u{00A0}', '\u{02C7}', '\u{02D8}', '\u{0141}', '\u{00A4}', '\u{0104}', '\u{00A6}', '\u{00A7}',
'\u{00A8}', '\u{00A9}', '\u{015E}', '\u{00AB}', '\u{00AC}', '\u{00AD}', '\u{00AE}', '\u{017B}',
'\u{00B0}', '\u{00B1}', '\u{02DB}', '\u{0142}', '\u{00B4}', '\u{00B5}', '\u{00B6}', '\u{00B7}',
'\u{00B8}', '\u{0105}', '\u{015F}', '\u{00BB}', '\u{013D}', '\u{02DD}', '\u{013E}', '\u{017C}',
'\u{0154}', '\u{00C1}', '\u{00C2}', '\u{0102}', '\u{00C4}', '\u{0139}', '\u{0106}', '\u{00C7}',
'\u{010C}', '\u{00C9}', '\u{0118}', '\u{00CB}', '\u{011A}', '\u{00CD}', '\u{010E}', '\u{0110}',
'\u{0143}', '\u{0147}', '\u{00D2}', '\u{00D3}', '\u{0150}', '\u{00D5}', '\u{00D6}', '\u{00D7}',
'\u{0158}', '\u{016E}', '\u{00DA}', '\u{0170}', '\u{00DC}', '\u{00DD}', '\u{0162}', '\u{00DF}',
'\u{0155}', '\u{00E1}', '\u{00E2}', '\u{0103}', '\u{00E4}', '\u{013A}', '\u{0107}', '\u{00E7}',
'\u{010D}', '\u{00E9}', '\u{0119}', '\u{00EB}', '\u{011B}', '\u{00ED}', '\u{010F}', '\u{0111}',
'\u{0144}', '\u{0148}', '\u{00F2}', '\u{00F3}', '\u{0151}', '\u{00F5}', '\u{00F6}', '\u{00F7}',
'\u{0159}', '\u{016F}', '\u{00FA}', '\u{0171}', '\u{00FC}', '\u{00FD}', '\u{0163}', '\u{02D9}',
];
fn encode_cp1250(text: &str) -> Vec<u8> {
let mut bytes = Vec::new();
for character in text.chars() {
let code = character as u32;
if code < 0x80 {
bytes.push(code as u8);
} else if let Some(at) = CP1250.iter().position(|c| *c == character) {
bytes.push(0x80 + at as u8);
} else {
bytes.push(b'?');
}
}
bytes
}
fn decode_cp1250(bytes: &[u8]) -> (String, usize) {
let mut text = String::new();
for byte in bytes {
text.push(if *byte < 0x80 { *byte as char } else { CP1250[*byte as usize - 0x80] });
}
(text, bytes.len())
}
pub(crate) fn encode(text: &str, encoding: Encoding) -> Vec<u8> {
match encoding {
Encoding::Cp1252 => encode_cp1252(text),
Encoding::Cp1250 => encode_cp1250(text),
Encoding::CodePage(page) => encode_code_page(text, page),
Encoding::Utf8 { .. } => text.as_bytes().to_vec(),
Encoding::Utf16 { .. } => {
let mut bytes = Vec::new();
for character in text.chars() {
let mut units = [0u16; 2];
for unit in character.encode_utf16(&mut units) {
bytes.extend_from_slice(&unit.to_le_bytes());
}
}
bytes
}
}
}
pub(crate) fn decode(bytes: &[u8], encoding: Encoding) -> Result<(String, usize), String> {
match encoding {
Encoding::Cp1252 => Ok(decode_cp1252(bytes)),
Encoding::Cp1250 => Ok(decode_cp1250(bytes)),
Encoding::CodePage(page) => Ok(decode_code_page(bytes, page)),
Encoding::Utf8 { .. } => decode_utf8(bytes),
Encoding::Utf16 { .. } => decode_utf16(bytes),
}
}
const CP437: [char; 128] = [
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}', '\u{00E7}',
'\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}', '\u{00EE}', '\u{00EC}', '\u{00C4}', '\u{00C5}',
'\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}', '\u{00F9}',
'\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00A2}', '\u{00A3}', '\u{00A5}', '\u{20A7}', '\u{0192}',
'\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}', '\u{00F1}', '\u{00D1}', '\u{00AA}', '\u{00BA}',
'\u{00BF}', '\u{2310}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}', '\u{00BB}',
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{2561}', '\u{2562}', '\u{2556}',
'\u{2555}', '\u{2563}', '\u{2551}', '\u{2557}', '\u{255D}', '\u{255C}', '\u{255B}', '\u{2510}',
'\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{255E}', '\u{255F}',
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{2567}',
'\u{2568}', '\u{2564}', '\u{2565}', '\u{2559}', '\u{2558}', '\u{2552}', '\u{2553}', '\u{256B}',
'\u{256A}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{258C}', '\u{2590}', '\u{2580}',
'\u{03B1}', '\u{00DF}', '\u{0393}', '\u{03C0}', '\u{03A3}', '\u{03C3}', '\u{00B5}', '\u{03C4}',
'\u{03A6}', '\u{0398}', '\u{03A9}', '\u{03B4}', '\u{221E}', '\u{03C6}', '\u{03B5}', '\u{2229}',
'\u{2261}', '\u{00B1}', '\u{2265}', '\u{2264}', '\u{2320}', '\u{2321}', '\u{00F7}', '\u{2248}',
'\u{00B0}', '\u{2219}', '\u{00B7}', '\u{221A}', '\u{207F}', '\u{00B2}', '\u{25A0}', '\u{00A0}',
];
fn encode_code_page(text: &str, page: u32) -> Vec<u8> {
if page != 437 {
return encode_cp1252(text);
}
let mut bytes = Vec::new();
for character in text.chars() {
let code = character as u32;
if code < 0x80 {
bytes.push(code as u8);
continue;
}
match CP437.iter().position(|other| *other == character) {
Some(at) => bytes.push(0x80 + at as u8),
None => bytes.push(b'?'),
}
}
bytes
}
fn decode_code_page(bytes: &[u8], page: u32) -> (String, usize) {
if page != 437 {
return decode_cp1252(bytes);
}
let mut text = String::new();
for byte in bytes {
let character = match byte {
0x80..=0xFF => CP437[(*byte - 0x80) as usize],
other => *other as char,
};
text.push(character);
}
(text, bytes.len())
}
fn decode_utf8(bytes: &[u8]) -> Result<(String, usize), String> {
match core::str::from_utf8(bytes) {
Ok(text) => Ok((text.to_string(), bytes.len())),
Err(error) if error.error_len().is_none() => {
let used = error.valid_up_to();
let text = core::str::from_utf8(&bytes[..used]).map_err(|_| broken())?;
Ok((text.to_string(), used))
}
Err(_) => Err(broken()),
}
}
fn decode_utf16(bytes: &[u8]) -> Result<(String, usize), String> {
let mut text = String::new();
let mut used = 0usize;
let mut lead: Option<u16> = None;
let mut index = 0usize;
while index + 1 < bytes.len() {
let unit = u16::from_le_bytes([bytes[index], bytes[index + 1]]);
match lead.take() {
Some(high) => {
if !(0xDC00..0xE000).contains(&unit) {
return Err(broken());
}
let code = 0x10000 + ((high as u32 - 0xD800) << 10) + (unit as u32 - 0xDC00);
text.push(char::from_u32(code).ok_or_else(broken)?);
used = index + 2;
}
None => {
if (0xD800..0xDC00).contains(&unit) {
lead = Some(unit);
} else if (0xDC00..0xE000).contains(&unit) {
return Err(broken());
} else {
text.push(char::from_u32(unit as u32).ok_or_else(broken)?);
used = index + 2;
}
}
}
index += 2;
}
Ok((text, used))
}
fn broken() -> String {
"the bytes of the file are not text in this encoding.".to_string()
}
fn take(text: &str, count: usize) -> (String, usize) {
match text.char_indices().nth(count) {
Some((at, _)) => (text[..at].to_string(), at),
None => (text.to_string(), text.len()),
}
}
fn line_of(bytes: &[u8], encoding: Encoding) -> Option<(usize, usize)> {
match encoding {
Encoding::Cp1252 | Encoding::Cp1250 | Encoding::CodePage(_) | Encoding::Utf8 { .. } => {
let at = bytes.iter().position(|byte| *byte == 0x0A)?;
let end = if at > 0 && bytes[at - 1] == 0x0D {
at - 1
} else {
at
};
Some((end, at + 1))
}
Encoding::Utf16 { .. } => {
let at = bytes
.windows(2)
.position(|pair| pair[0] == 0x0A && pair[1] == 0x00)?;
let end = if at >= 2 && bytes[at - 2] == 0x0D && bytes[at - 1] == 0x00 {
at - 2
} else {
at
};
Some((end, at + 2))
}
}
}
fn little(bytes: &[u8]) -> u64 {
bytes
.iter()
.fold(0u64, |acc, byte| (acc << 8) | *byte as u64)
}
fn little_bytes(number: u64, count: usize) -> Vec<u8> {
let mut bytes = vec![0u8; count];
for (index, byte) in bytes.iter_mut().rev().enumerate() {
*byte = ((number >> (index * 8)) & 0xFF) as u8;
}
bytes
}
fn float_bytes(number: f64, single: bool) -> Vec<u8> {
if single {
little_bytes((number as f32).to_bits() as u64, 4)
} else {
little_bytes(number.to_bits(), 8)
}
}
fn base_method(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let Value::Object(object) = this else {
return None;
};
let failure = |message: &str| {
Some(Err(RuntimeFailure::Error(RuntimeError {
message: message.to_string(),
line,
})))
};
let name = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let key = name.to_lowercase();
match method {
"ownprops" => {
let pairs: Vec<(Value, Value)> = object
.borrow()
.properties
.iter()
.filter(|(name, _)| name.as_str() != STATE)
.map(|(_, property)| (Value::Text(property.name.clone()), property.value.clone()))
.collect();
Some(Ok(enumerator::make(pairs, enumerator::Alone::TheKey)))
}
"hasownprop" => Some(Ok(Value::Int(own_property(object, &key) as i64))),
"hasprop" => Some(Ok(Value::Int(
(PROPERTIES.contains(&key.as_str())
|| METHODS.contains(&key.as_str())
|| own_property(object, &key)
|| key == "__class"
|| key == "__init"
|| key == "base") as i64,
))),
"hasmethod" => Some(Ok(Value::Int(
(METHODS.contains(&key.as_str())
|| key == "__init") as i64,
))),
"getownpropdesc" => {
let name = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let value = object.borrow().value_of(&key);
match value {
Some(value) => {
let table = match rt.the_members_of_a_descriptor(&value) {
Some(members) => members,
None => {
let mut table = BTreeMap::new();
put(&mut table, "value", value);
table
}
};
Some(Ok(Value::Object(SharedCell::new(Object {
class: "object".to_string(),
properties: table,
}))))
}
None => Some(Err(rt.no_property(this, &name, line))),
}
}
"defineprop" => {
if key == STATE {
return failure("the state of a file is not a property of it.");
}
let descriptor = match rt.the_descriptor(arguments.get(1), line) {
Ok(descriptor) => descriptor,
Err(failure) => return Some(Err(failure)),
};
put(&mut object.borrow_mut().properties, &name, descriptor);
Some(Ok(this.clone()))
}
"deleteprop" => {
if key == STATE {
return Some(Ok(Value::Text(String::new())));
}
let gone = object
.borrow_mut()
.properties
.remove(&key)
.map(|property| property.value);
Some(Ok(match gone {
None => Value::Text(String::new()),
Some(value) => match rt.the_value_of_the_descriptor(&value, this, &name, line) {
Ok(Some(value)) => value,
_ => value,
},
}))
}
_ => None,
}
}
fn own_property(object: &SharedCell<Object>, key: &str) -> bool {
key != STATE && object.borrow().properties.contains_key(key)
}