|
| 1 | +#![allow(dead_code)] |
| 2 | + |
| 3 | +use super::error::{IntoException as _, TypeError, ValueResult}; |
| 4 | +use bytemuck::{AnyBitPattern, NoUninit}; |
| 5 | +use spacetimedb_sats::{i256, u256}; |
| 6 | +use v8::{BigInt, Boolean, HandleScope, Int32, Local, Number, Uint32, Value}; |
| 7 | + |
| 8 | +/// Types that a v8 [`Value`] can be converted into. |
| 9 | +pub(super) trait FromValue: Sized { |
| 10 | + /// Converts `val` in `scope` to `Self` if possible. |
| 11 | + fn from_value<'s>(val: Local<'_, Value>, scope: &mut HandleScope<'s>) -> ValueResult<'s, Self>; |
| 12 | +} |
| 13 | + |
| 14 | +/// Provides a [`FromValue`] implementation. |
| 15 | +macro_rules! impl_from_value { |
| 16 | + ($ty:ty, ($val:ident, $scope:ident) => $logic:expr) => { |
| 17 | + impl FromValue for $ty { |
| 18 | + fn from_value<'s>($val: Local<'_, Value>, $scope: &mut HandleScope<'s>) -> ValueResult<'s, Self> { |
| 19 | + $logic |
| 20 | + } |
| 21 | + } |
| 22 | + }; |
| 23 | +} |
| 24 | + |
| 25 | +/// Tries to cast `Value` into `T` or raises a JS exception as a returned `Err` value. |
| 26 | +fn try_cast<'a, 'b, T>( |
| 27 | + scope: &mut HandleScope<'a>, |
| 28 | + val: Local<'b, Value>, |
| 29 | + on_err: impl FnOnce(&str) -> String, |
| 30 | +) -> ValueResult<'a, Local<'b, T>> |
| 31 | +where |
| 32 | + Local<'b, T>: TryFrom<Local<'b, Value>>, |
| 33 | +{ |
| 34 | + val.try_cast::<T>() |
| 35 | + .map_err(|_| TypeError(on_err(val.type_repr())).into_exception(scope)) |
| 36 | +} |
| 37 | + |
| 38 | +/// Tries to cast `Value` into `T` or raises a JS exception as a returned `Err` value. |
| 39 | +macro_rules! cast { |
| 40 | + ($scope:expr, $val:expr, $js_ty:ty, $expected:literal $(, $args:expr)* $(,)?) => {{ |
| 41 | + try_cast::<$js_ty>($scope, $val, |got| format!(concat!("Expected ", $expected, ", got {__got}"), $($args,)* __got = got)) |
| 42 | + }}; |
| 43 | +} |
| 44 | +pub(super) use cast; |
| 45 | + |
| 46 | +/// Returns a JS exception value indicating that a value overflowed |
| 47 | +/// when converting to the type `rust_ty`. |
| 48 | +fn value_overflowed<'s>(rust_ty: &str, scope: &mut HandleScope<'s>) -> Local<'s, Value> { |
| 49 | + TypeError(format!("Value overflowed `{rust_ty}`")).into_exception(scope) |
| 50 | +} |
| 51 | + |
| 52 | +/// Returns a JS exception value indicating that a value underflowed |
| 53 | +/// when converting to the type `rust_ty`. |
| 54 | +fn value_underflowed<'s>(rust_ty: &str, scope: &mut HandleScope<'s>) -> Local<'s, Value> { |
| 55 | + TypeError(format!("Value underflowed `{rust_ty}`")).into_exception(scope) |
| 56 | +} |
| 57 | + |
| 58 | +// `FromValue for bool`. |
| 59 | +impl_from_value!(bool, (val, scope) => cast!(scope, val, Boolean, "boolean").map(|b| b.is_true())); |
| 60 | + |
| 61 | +// `FromValue for u8, u16, u32, i8, i16, i32`. |
| 62 | +macro_rules! int32_from_value { |
| 63 | + ($js_ty:ty, $rust_ty:ty) => { |
| 64 | + impl_from_value!($rust_ty, (val, scope) => { |
| 65 | + let num = cast!(scope, val, $js_ty, "number for `{}`", stringify!($rust_ty))?; |
| 66 | + num.value().try_into().map_err(|_| value_overflowed(stringify!($rust_ty), scope)) |
| 67 | + }); |
| 68 | + } |
| 69 | +} |
| 70 | +int32_from_value!(Uint32, u8); |
| 71 | +int32_from_value!(Uint32, u16); |
| 72 | +int32_from_value!(Uint32, u32); |
| 73 | +int32_from_value!(Int32, i8); |
| 74 | +int32_from_value!(Int32, i16); |
| 75 | +int32_from_value!(Int32, i32); |
| 76 | + |
| 77 | +// `FromValue for f32, f64`. |
| 78 | +// |
| 79 | +// Note that, as per the rust-reference, |
| 80 | +// - "Casting from an f64 to an f32 will produce the closest possible f32" |
| 81 | +// https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.numeric.float-narrowing |
| 82 | +macro_rules! float_from_value { |
| 83 | + ($rust_ty:ty) => { |
| 84 | + impl_from_value!($rust_ty, (val, scope) => { |
| 85 | + cast!(scope, val, Number, "number for `{}`", stringify!($rust_ty)).map(|n| n.value() as _) |
| 86 | + }); |
| 87 | + } |
| 88 | +} |
| 89 | +float_from_value!(f32); |
| 90 | +float_from_value!(f64); |
| 91 | + |
| 92 | +// `FromValue for u64, i64`. |
| 93 | +macro_rules! int64_from_value { |
| 94 | + ($rust_ty:ty, $conv_method: ident) => { |
| 95 | + impl_from_value!($rust_ty, (val, scope) => { |
| 96 | + let rust_ty = stringify!($rust_ty); |
| 97 | + let bigint = cast!(scope, val, BigInt, "bigint for `{}`", rust_ty)?; |
| 98 | + let (val, ok) = bigint.$conv_method(); |
| 99 | + ok.then_some(val).ok_or_else(|| value_overflowed(rust_ty, scope)) |
| 100 | + }); |
| 101 | + } |
| 102 | +} |
| 103 | +int64_from_value!(u64, u64_value); |
| 104 | +int64_from_value!(i64, i64_value); |
| 105 | + |
| 106 | +/// Converts `bigint` into its signnedness and its list of bytes in little-endian, |
| 107 | +/// or errors on overflow or unwanted signedness. |
| 108 | +/// |
| 109 | +/// Parameters: |
| 110 | +/// - `N` are the number of bytes to accept at most. |
| 111 | +/// - `W = N / 8` are the number of words to accept at most. |
| 112 | +/// - `UNSIGNED` is `true` if only unsigned integers are accepted. |
| 113 | +/// - `rust_ty` is the target type as a string, for errors. |
| 114 | +/// - `scope` for any JS exceptions that need to be raised. |
| 115 | +/// - `bigint` is the integer to convert. |
| 116 | +fn bigint_to_bytes<'s, const N: usize, const W: usize, const UNSIGNED: bool>( |
| 117 | + rust_ty: &str, |
| 118 | + scope: &mut HandleScope<'s>, |
| 119 | + bigint: &BigInt, |
| 120 | +) -> ValueResult<'s, (bool, [u8; N])> |
| 121 | +where |
| 122 | + [[u8; 8]; W]: NoUninit, |
| 123 | + [u8; N]: AnyBitPattern, |
| 124 | +{ |
| 125 | + // Read the words. |
| 126 | + let mut words = [0u64; W]; |
| 127 | + let (sign, _) = bigint.to_words_array(&mut words); |
| 128 | + |
| 129 | + if bigint.word_count() > W { |
| 130 | + // There's an under-/over-flow if the caller cannot handle that many words. |
| 131 | + return Err(if sign { |
| 132 | + value_underflowed(rust_ty, scope) |
| 133 | + } else { |
| 134 | + value_overflowed(rust_ty, scope) |
| 135 | + }); |
| 136 | + } |
| 137 | + |
| 138 | + if sign && UNSIGNED { |
| 139 | + // There's an overflow if the caller cannot accept negative numbers. |
| 140 | + return Err(value_overflowed(rust_ty, scope)); |
| 141 | + } |
| 142 | + |
| 143 | + // convert the words to little-endian bytes. |
| 144 | + let bytes = bytemuck::must_cast(words.map(|w| w.to_le_bytes())); |
| 145 | + Ok((sign, bytes)) |
| 146 | +} |
| 147 | + |
| 148 | +// `FromValue for u128, u256`. |
| 149 | +macro_rules! unsigned_bigint_from_value { |
| 150 | + ($rust_ty:ty, $bytes:literal, $words:literal) => { |
| 151 | + impl_from_value!($rust_ty, (val, scope) => { |
| 152 | + let rust_ty = stringify!($rust_ty); |
| 153 | + let bigint = cast!(scope, val, v8::BigInt, "bigint for `{}`", rust_ty)?; |
| 154 | + if let (val, true) = bigint.u64_value() { |
| 155 | + // Fast path. |
| 156 | + return Ok(val.into()); |
| 157 | + } |
| 158 | + let (_, bytes) = bigint_to_bytes::<$bytes, $words, true>(rust_ty, scope, &bigint)?; |
| 159 | + Ok(Self::from_le_bytes(bytes)) |
| 160 | + }); |
| 161 | + }; |
| 162 | +} |
| 163 | +unsigned_bigint_from_value!(u128, 16, 2); |
| 164 | +unsigned_bigint_from_value!(u256, 32, 4); |
| 165 | + |
| 166 | +// `FromValue for i128, i256`. |
| 167 | +macro_rules! signed_bigint_from_value { |
| 168 | + ($rust_ty:ty, $bytes:literal, $words:literal) => { |
| 169 | + impl_from_value!($rust_ty, (val, scope) => { |
| 170 | + let rust_ty = stringify!($rust_ty); |
| 171 | + let bigint = cast!(scope, val, v8::BigInt, "bigint for `{}`", rust_ty)?; |
| 172 | + if let (val, true) = bigint.i64_value() { |
| 173 | + // Fast path. |
| 174 | + return Ok(val.into()); |
| 175 | + } |
| 176 | + let (sign, bytes) = bigint_to_bytes::<$bytes, $words, false>(rust_ty, scope, &bigint)?; |
| 177 | + let x = Self::from_le_bytes(bytes); |
| 178 | + Ok(if sign { |
| 179 | + // A negative number, but we have a positive number `x`, so we want `-x`. |
| 180 | + // If that's not possible, and as we know there's no underflow, we have `MIN`. |
| 181 | + x.checked_neg().unwrap_or(Self::MIN) |
| 182 | + } else { |
| 183 | + x |
| 184 | + }) |
| 185 | + }); |
| 186 | + }; |
| 187 | +} |
| 188 | +signed_bigint_from_value!(i128, 16, 2); |
| 189 | +signed_bigint_from_value!(i256, 32, 4); |
0 commit comments