use std::cell::RefCell;
use std::fmt;
use js_gc::{Gc, Trace, Tracer};
use crate::object::JsObject;
#[derive(Clone)]
pub struct Wtf8 {
bytes: Box<[u8]>,
valid: bool,
}
impl Wtf8 {
pub fn new(text: impl Into<String>) -> Wtf8 {
Wtf8 {
bytes: text.into().into_bytes().into_boxed_slice(),
valid: true,
}
}
pub fn from_units(units: &[u16]) -> Wtf8 {
let mut bytes = Vec::with_capacity(units.len());
let mut valid = true;
let mut index = 0;
while index < units.len() {
let unit = units[index];
match units.get(index + 1) {
Some(&low) if is_high(unit) && is_low(low) => {
push_code_point(&mut bytes, combine(unit, low));
index += 2;
}
_ if is_surrogate(unit) => {
valid = false;
push_surrogate(&mut bytes, unit);
index += 1;
}
_ => {
push_code_point(&mut bytes, unit as u32);
index += 1;
}
}
}
Wtf8 {
bytes: bytes.into_boxed_slice(),
valid,
}
}
pub fn as_str(&self) -> Option<&str> {
if self.valid {
Some(unsafe { std::str::from_utf8_unchecked(&self.bytes) })
} else {
None
}
}
pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
match self.as_str() {
Some(text) => std::borrow::Cow::Borrowed(text),
None => String::from_utf8_lossy(&self.bytes),
}
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn to_units(&self) -> Vec<u16> {
let mut units = Vec::with_capacity(self.utf16_len());
self.push_units(&mut units);
units
}
pub fn utf16_len(&self) -> usize {
self.bytes
.iter()
.filter(|byte| (**byte & 0xC0) != 0x80)
.map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
.sum()
}
pub fn code_unit_at(&self, index: usize) -> Option<u16> {
let mut position = 0;
let mut at = 0;
while at < self.bytes.len() {
let (units, count, width) = self.sequence_at(at);
if position + count > index {
return Some(units[index - position]);
}
position += count;
at += width;
}
None
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
self.code_unit_at(index)
.map(|unit| Wtf8::from_units(&[unit]))
}
pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
let units = self.to_units();
let start = start.min(units.len());
let end = end.clamp(start, units.len());
Wtf8::from_units(&units[start..end])
}
pub fn code_points(&self) -> Vec<Wtf8> {
let mut out = Vec::new();
let mut at = 0;
while at < self.bytes.len() {
let (_, _, width) = self.sequence_at(at);
let mut bytes = Vec::with_capacity(width);
bytes.extend_from_slice(&self.bytes[at..at + width]);
out.push(Wtf8 {
valid: std::str::from_utf8(&bytes).is_ok(),
bytes: bytes.into_boxed_slice(),
});
at += width;
}
out
}
pub fn concat(&self, other: &Wtf8) -> Wtf8 {
let bridges =
ends_with_high_surrogate(&self.bytes) && starts_with_low_surrogate(&other.bytes);
if !bridges {
let mut bytes = Vec::with_capacity(self.bytes.len() + other.bytes.len());
bytes.extend_from_slice(&self.bytes);
bytes.extend_from_slice(&other.bytes);
return Wtf8 {
bytes: bytes.into_boxed_slice(),
valid: self.valid && other.valid,
};
}
let mut units = self.to_units();
units.extend(other.to_units());
Wtf8::from_units(&units)
}
fn push_units(&self, out: &mut Vec<u16>) {
let mut at = 0;
while at < self.bytes.len() {
let (units, count, width) = self.sequence_at(at);
out.extend_from_slice(&units[..count]);
at += width;
}
}
pub fn code_point_values(&self) -> Vec<u32> {
self.code_points()
.into_iter()
.map(|point| match point.as_str() {
Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
})
.collect()
}
fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
let byte = self.bytes[at];
let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
if byte < 0x80 {
([byte as u16, 0], 1, 1)
} else if byte >> 5 == 0b110 {
(
[
(((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
0,
],
1,
2,
)
} else if byte >> 4 == 0b1110 {
(
[
((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
as u16,
0,
],
1,
3,
)
} else {
let code = (byte as u32 & 0x07) << 18
| ((byte_at(1) & 0x3F) << 12)
| ((byte_at(2) & 0x3F) << 6)
| (byte_at(3) & 0x3F);
let code = code.wrapping_sub(0x10000);
(
[
0xD800u16.wrapping_add((code >> 10) as u16),
0xDC00u16.wrapping_add((code & 0x3FF) as u16),
],
2,
4,
)
}
}
}
fn is_surrogate(unit: u16) -> bool {
(0xD800..0xE000).contains(&unit)
}
fn is_high(unit: u16) -> bool {
(0xD800..0xDC00).contains(&unit)
}
fn is_low(unit: u16) -> bool {
(0xDC00..0xE000).contains(&unit)
}
fn combine(high: u16, low: u16) -> u32 {
0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
}
fn push_code_point(out: &mut Vec<u8>, code: u32) {
if code < 0x80 {
out.push(code as u8);
} else if code < 0x800 {
out.push(0xC0 | (code >> 6) as u8);
out.push(0x80 | (code & 0x3F) as u8);
} else if code < 0x10000 {
out.push(0xE0 | (code >> 12) as u8);
out.push(0x80 | ((code >> 6) & 0x3F) as u8);
out.push(0x80 | (code & 0x3F) as u8);
} else {
out.push(0xF0 | (code >> 18) as u8);
out.push(0x80 | ((code >> 12) & 0x3F) as u8);
out.push(0x80 | ((code >> 6) & 0x3F) as u8);
out.push(0x80 | (code & 0x3F) as u8);
}
}
fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
out.push(0xE0 | (unit >> 12) as u8);
out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
out.push(0x80 | (unit & 0x3F) as u8);
}
fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
let len = bytes.len();
len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
}
fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
}
impl PartialEq for Wtf8 {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for Wtf8 {}
impl fmt::Debug for Wtf8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.to_string_lossy())
}
}
pub struct JsString {
text: Wtf8,
units: RefCell<Option<std::rc::Rc<Vec<u16>>>>,
}
impl JsString {
pub fn new(text: impl Into<String>) -> JsString {
JsString {
text: Wtf8::new(text),
units: RefCell::new(None),
}
}
pub fn from_wtf8(text: Wtf8) -> JsString {
JsString {
text,
units: RefCell::new(None),
}
}
pub fn units_cached(&self) -> std::rc::Rc<Vec<u16>> {
if let Some(units) = self.units.borrow().as_ref() {
return units.clone();
}
let units = std::rc::Rc::new(self.text.to_units());
*self.units.borrow_mut() = Some(units.clone());
units
}
pub fn code_unit_at(&self, index: usize) -> Option<u16> {
self.units_cached().get(index).copied()
}
pub fn wtf8(&self) -> &Wtf8 {
&self.text
}
pub fn as_str(&self) -> Option<&str> {
self.text.as_str()
}
pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
self.text.to_string_lossy()
}
pub fn to_units(&self) -> Vec<u16> {
self.units_cached().as_ref().clone()
}
pub fn utf16_len(&self) -> usize {
self.text.utf16_len()
}
}
impl Trace for JsString {
fn trace(&self, _tracer: &mut Tracer) {}
}
impl fmt::Debug for JsString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.text)
}
}
pub struct JsSymbol {
description: Option<String>,
registry_key: Option<String>,
}
impl JsSymbol {
pub fn new(description: Option<String>) -> JsSymbol {
JsSymbol {
description,
registry_key: None,
}
}
pub fn registered(key: String) -> JsSymbol {
JsSymbol {
description: Some(key.clone()),
registry_key: Some(key),
}
}
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
pub fn registry_key(&self) -> Option<&str> {
self.registry_key.as_deref()
}
pub fn to_display_string(&self) -> String {
match &self.description {
Some(text) => format!("Symbol({text})"),
None => "Symbol()".to_string(),
}
}
}
impl Trace for JsSymbol {
fn trace(&self, _tracer: &mut Tracer) {}
}
impl fmt::Debug for JsSymbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_display_string())
}
}
pub struct Cell {
value: RefCell<Value>,
}
impl Cell {
pub fn new(value: Value) -> Cell {
Cell {
value: RefCell::new(value),
}
}
pub fn get(&self) -> Value {
self.value.borrow().clone()
}
pub fn set(&self, value: Value) {
*self.value.borrow_mut() = value;
}
}
impl Trace for Cell {
fn trace(&self, tracer: &mut Tracer) {
self.value.borrow().trace(tracer);
}
}
#[derive(Clone)]
pub enum Value {
Undefined,
Null,
Bool(bool),
Int(i32),
Float(f64),
String(Gc<JsString>),
Object(Gc<JsObject>),
Symbol(Gc<JsSymbol>),
BigInt(Gc<crate::bigint::BigInt>),
CatchOffset(u32),
ReturnAddress(u32),
Hole,
Uninitialized,
}
impl Value {
pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
Value::String(Gc::new(heap, JsString::new(text)))
}
pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
Value::String(Gc::new(heap, JsString::from_wtf8(text)))
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Int(i) => Some(*i as f64),
Value::Float(f) => Some(*f),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => s.as_str(),
_ => None,
}
}
pub fn as_wtf8(&self) -> Option<&Wtf8> {
match self {
Value::String(s) => Some(s.wtf8()),
_ => None,
}
}
pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
match self {
Value::Symbol(symbol) => Some(symbol),
_ => None,
}
}
pub fn as_object(&self) -> Option<&Gc<JsObject>> {
match self {
Value::Object(o) => Some(o),
_ => None,
}
}
pub fn is_nullish(&self) -> bool {
matches!(self, Value::Undefined | Value::Null)
}
pub fn type_of(&self) -> &'static str {
match self {
Value::Undefined => "undefined",
Value::Null => "object",
Value::Bool(_) => "boolean",
Value::Int(_) | Value::Float(_) => "number",
Value::String(_) => "string",
Value::Symbol(_) => "symbol",
Value::BigInt(_) => "bigint",
Value::Object(object) => {
if object.is_callable() {
"function"
} else {
"object"
}
}
Value::Uninitialized
| Value::Hole
| Value::CatchOffset(_)
| Value::ReturnAddress(_) => "undefined",
}
}
pub fn to_boolean(&self) -> bool {
match self {
Value::Undefined | Value::Null => false,
Value::Bool(b) => *b,
Value::Int(i) => *i != 0,
Value::Float(f) => *f != 0.0 && !f.is_nan(),
Value::String(s) => !s.wtf8().is_empty(),
Value::Symbol(_) => true,
Value::BigInt(big) => !big.is_zero(),
Value::Object(_) => true,
Value::Uninitialized
| Value::Hole
| Value::CatchOffset(_)
| Value::ReturnAddress(_) => false,
}
}
pub fn to_number(&self) -> f64 {
match self {
Value::Undefined => f64::NAN,
Value::Null => 0.0,
Value::Bool(b) => {
if *b {
1.0
} else {
0.0
}
}
Value::Int(i) => *i as f64,
Value::Float(f) => *f,
Value::String(s) => string_to_number(&s.to_string_lossy()),
Value::Symbol(_) => f64::NAN,
Value::BigInt(_) => f64::NAN,
Value::Object(_) => f64::NAN,
Value::Uninitialized
| Value::Hole
| Value::CatchOffset(_)
| Value::ReturnAddress(_) => f64::NAN,
}
}
pub fn to_int32(&self) -> i32 {
to_int32(self.to_number())
}
pub fn to_uint32(&self) -> u32 {
self.to_int32() as u32
}
pub fn to_js_string(&self) -> String {
match self {
Value::Undefined => "undefined".to_string(),
Value::Null => "null".to_string(),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
Value::Int(i) => i.to_string(),
Value::Float(f) => number_to_string(*f),
Value::String(s) => s.to_string_lossy().into_owned(),
Value::BigInt(big) => big.to_decimal_string(),
Value::Symbol(s) => s.to_display_string(),
Value::Object(_) => "[object Object]".to_string(),
Value::Uninitialized
| Value::Hole
| Value::CatchOffset(_)
| Value::ReturnAddress(_) => "undefined".to_string(),
}
}
pub fn strict_equals(&self, other: &Value) -> bool {
match (self, other) {
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
let (a, b) = (self.to_number(), other.to_number());
a == b
}
(Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
(Value::BigInt(a), Value::BigInt(b)) => **a == **b,
(Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
(Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
_ => false,
}
}
pub fn same_value(&self, other: &Value) -> bool {
if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
let (a, b) = (self.to_number(), other.to_number());
if a.is_nan() && b.is_nan() {
return true;
}
if a == 0.0 && b == 0.0 {
return a.is_sign_negative() == b.is_sign_negative();
}
return a == b;
}
self.strict_equals(other)
}
pub fn same_value_zero(&self, other: &Value) -> bool {
if let (Value::Float(a), Value::Float(b)) = (self, other)
&& a.is_nan()
&& b.is_nan()
{
return true;
}
self.strict_equals(other)
}
pub fn loose_equals(&self, other: &Value) -> bool {
if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
return match (self, other) {
(Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
_ => primitive_loose_equals(&self.primitive(), &other.primitive()),
};
}
match (self, other) {
(Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
(Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
(Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
(Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::BigInt(a), Value::BigInt(b)) => **a == **b,
(Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
}
(Value::BigInt(a), other) => match other {
Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
_ => false,
},
(other, Value::BigInt(b)) => match other {
Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
_ => false,
},
_ => self.to_number() == other.to_number(),
}
}
fn primitive(&self) -> Primitive {
match self {
Value::Undefined => Primitive::Undefined,
Value::Null => Primitive::Null,
Value::Bool(b) => Primitive::Bool(*b),
Value::Int(i) => Primitive::Number(*i as f64),
Value::Float(f) => Primitive::Number(*f),
Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
Value::Symbol(s) => Primitive::Symbol(s.clone()),
Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
Value::Object(_) => Primitive::String(self.to_js_string()),
Value::Uninitialized
| Value::Hole
| Value::CatchOffset(_)
| Value::ReturnAddress(_) => Primitive::Undefined,
}
}
}
enum Primitive {
Undefined,
Null,
Bool(bool),
Number(f64),
String(String),
Symbol(Gc<JsSymbol>),
}
fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
use Primitive::*;
match (left, right) {
(Undefined | Null, Undefined | Null) => true,
(Undefined | Null, _) | (_, Undefined | Null) => false,
(Symbol(a), Symbol(b)) => a.ptr_eq(b),
(Symbol(_), _) | (_, Symbol(_)) => false,
(String(a), String(b)) => a == b,
(Bool(a), Bool(b)) => a == b,
(Number(a), Number(b)) => a == b,
(String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
(Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
(Bool(b), String(s)) | (String(s), Bool(b)) => {
string_to_number(s) == (if *b { 1.0 } else { 0.0 })
}
}
}
fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
number.is_finite()
&& number.fract() == 0.0
&& crate::bigint::BigInt::from_f64_truncated(number) == *big
}
pub fn to_int32(value: f64) -> i32 {
if !value.is_finite() || value == 0.0 {
return 0;
}
let truncated = value.trunc();
let modulo = truncated.rem_euclid(4294967296.0);
let wrapped = if modulo >= 2147483648.0 {
modulo - 4294967296.0
} else {
modulo
};
wrapped as i32
}
pub fn string_to_number(text: &str) -> f64 {
let trimmed = text.trim();
if trimmed.is_empty() {
return 0.0;
}
if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
return radix_number(rest, 16);
}
if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
return radix_number(rest, 8);
}
if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
return radix_number(rest, 2);
}
let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
Some(rest) => (&trimmed[..1], rest),
None => ("", trimmed),
};
if digits == "Infinity" {
return if sign == "-" {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
}
if !is_decimal_literal(digits) {
return f64::NAN;
}
trimmed.parse::<f64>().unwrap_or(f64::NAN)
}
fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
text.strip_prefix(lower)
.or_else(|| text.strip_prefix(upper))
}
fn radix_number(digits: &str, radix: u32) -> f64 {
if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
return f64::NAN;
}
match u64::from_str_radix(digits, radix) {
Ok(value) => value as f64,
Err(_) => digits.chars().fold(0.0, |acc, c| {
acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
}),
}
}
fn is_decimal_literal(text: &str) -> bool {
let bytes = text.as_bytes();
let mut index = 0;
let mut digits = 0;
while index < bytes.len() && bytes[index].is_ascii_digit() {
index += 1;
digits += 1;
}
if index < bytes.len() && bytes[index] == b'.' {
index += 1;
while index < bytes.len() && bytes[index].is_ascii_digit() {
index += 1;
digits += 1;
}
}
if digits == 0 {
return false;
}
if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
index += 1;
if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
index += 1;
}
let start = index;
while index < bytes.len() && bytes[index].is_ascii_digit() {
index += 1;
}
if index == start {
return false;
}
}
index == bytes.len()
}
pub fn number_to_string(value: f64) -> String {
if value.is_nan() {
return "NaN".to_string();
}
if value.is_infinite() {
return if value > 0.0 {
"Infinity".to_string()
} else {
"-Infinity".to_string()
};
}
if value == 0.0 {
return "0".to_string();
}
let magnitude = value.abs();
if magnitude >= 1e21 || magnitude < 1e-6 {
return normalise_exponent(format!("{value:e}"));
}
format!("{value}")
}
pub fn number_to_string_for_print(value: f64) -> String {
if value == 0.0 && value.is_sign_negative() {
return "-0".to_string();
}
number_to_string(value)
}
fn normalise_exponent(text: String) -> String {
let Some((mantissa, exponent)) = text.split_once('e') else {
return text;
};
if exponent.starts_with('-') {
text
} else {
let digits = exponent.strip_prefix('+').unwrap_or(exponent);
format!("{mantissa}e+{digits}")
}
}
impl Trace for Value {
fn trace(&self, tracer: &mut Tracer) {
match self {
Value::String(s) => tracer.visit(s),
Value::Object(o) => tracer.visit(o),
Value::Symbol(s) => tracer.visit(s),
_ => {}
}
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Undefined => f.write_str("undefined"),
Value::Null => f.write_str("null"),
Value::Bool(b) => write!(f, "{b}"),
Value::Int(i) => write!(f, "{i}"),
Value::Float(x) => write!(f, "{}", number_to_string(*x)),
Value::String(s) => write!(f, "{:?}", s.as_str()),
Value::Object(_) => f.write_str("[object]"),
Value::Symbol(s) => f.write_str(&s.to_display_string()),
Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
Value::Uninitialized => f.write_str("<uninitialised>"),
Value::Hole => f.write_str("<hole>"),
Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn int32_wraps_the_way_the_spec_says() {
assert_eq!(to_int32(0.0), 0);
assert_eq!(to_int32(f64::NAN), 0);
assert_eq!(to_int32(f64::INFINITY), 0);
assert_eq!(to_int32(1.9), 1);
assert_eq!(to_int32(-1.9), -1);
assert_eq!(to_int32(2147483648.0), -2147483648);
assert_eq!(to_int32(4294967296.0), 0);
assert_eq!(to_int32(-4294967297.0), -1);
}
#[test]
fn numbers_print_like_javascript() {
assert_eq!(number_to_string(0.0), "0");
assert_eq!(number_to_string(-0.0), "0");
assert_eq!(number_to_string(1.0), "1");
assert_eq!(number_to_string(-1.5), "-1.5");
assert_eq!(number_to_string(1e21), "1e+21");
assert_eq!(number_to_string(1e-7), "1e-7");
assert_eq!(number_to_string(1e-6), "0.000001");
assert_eq!(number_to_string(1e20), "100000000000000000000");
assert_eq!(number_to_string(5e-324), "5e-324");
assert_eq!(number_to_string_for_print(-0.0), "-0");
assert_eq!(number_to_string(f64::NAN), "NaN");
assert_eq!(number_to_string(f64::INFINITY), "Infinity");
assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
}
#[test]
fn strings_parse_to_numbers_without_prefix_matching() {
assert_eq!(string_to_number(""), 0.0);
assert_eq!(string_to_number(" "), 0.0);
assert_eq!(string_to_number(" 42 "), 42.0);
assert_eq!(string_to_number("0x10"), 16.0);
assert_eq!(string_to_number("0b101"), 5.0);
assert_eq!(string_to_number("0o17"), 15.0);
assert_eq!(string_to_number("Infinity"), f64::INFINITY);
assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
assert_eq!(string_to_number("1e3"), 1000.0);
assert_eq!(string_to_number(".5"), 0.5);
assert_eq!(string_to_number("5."), 5.0);
assert!(string_to_number("12px").is_nan());
assert!(string_to_number("inf").is_nan());
assert!(string_to_number("nan").is_nan());
assert!(string_to_number("1e").is_nan());
assert!(string_to_number("0x").is_nan());
}
#[test]
fn strict_equality_ignores_the_int_float_split() {
assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
assert!(!Value::Int(0).strict_equals(&Value::Null));
assert!(!Value::Undefined.strict_equals(&Value::Null));
}
#[test]
fn falsy_values_are_the_spec_list() {
assert!(!Value::Undefined.to_boolean());
assert!(!Value::Null.to_boolean());
assert!(!Value::Bool(false).to_boolean());
assert!(!Value::Int(0).to_boolean());
assert!(!Value::Float(f64::NAN).to_boolean());
assert!(!Value::Float(-0.0).to_boolean());
assert!(Value::Float(0.1).to_boolean());
}
}