1use crate::{
2 convert::List, Array, CString, Ctx, Error, FromAtom, FromJs, Object, Result, StdString, String,
3 Type, Utf8, Value,
4};
5use alloc::{
6 boxed::Box,
7 collections::{BTreeMap, BTreeSet, LinkedList, VecDeque},
8 rc::Rc,
9 sync::Arc,
10 vec::Vec,
11};
12#[allow(unused_imports)]
13use core::{
14 cell::{Cell, RefCell},
15 hash::{BuildHasher, Hash},
16 time::Duration,
17};
18use hashbrown::{HashMap as HashbrownMap, HashSet as HashbrownSet};
19
20#[cfg(feature = "std")]
21use std::{
22 collections::{HashMap, HashSet},
23 sync::{Mutex, RwLock},
24 time::SystemTime,
25};
26
27#[cfg(feature = "either")]
28use either::{Either, Left, Right};
29
30#[cfg(feature = "indexmap")]
31use indexmap::{IndexMap, IndexSet};
32
33impl<'js> FromJs<'js> for Value<'js> {
34 fn from_js(_: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
35 Ok(value)
36 }
37}
38
39impl<'js> FromJs<'js> for StdString {
40 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
41 String::from_value(value).and_then(|string| string.to_string())
42 }
43}
44
45impl<'js> FromJs<'js> for char {
46 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
47 let type_name = value.type_name();
48 let s = String::from_value(value)?.to_string()?;
49
50 let mut chars = s.chars();
51 let (c, more) = (chars.next(), chars.next());
52
53 match (c, more) {
54 (Some(c), None) => Ok(c),
55 _ => Err(Error::FromJs {
56 from: type_name,
57 to: "char",
58 message: Some("The length of the string converted to char must be 1".into()),
59 }),
60 }
61 }
62}
63
64impl<'js> FromJs<'js> for CString<'js> {
65 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
66 String::from_value(value)?.to_cstring()
67 }
68}
69
70impl<'js> FromJs<'js> for CString<'js, Utf8> {
71 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
72 String::from_value(value)?.to_cstring()?.validate()
73 }
74}
75
76impl<'js> FromJs<'js> for () {
78 fn from_js(_: &Ctx<'js>, _: Value<'js>) -> Result<Self> {
79 Ok(())
80 }
81}
82
83impl<'js, T> FromJs<'js> for Option<T>
85where
86 T: FromJs<'js>,
87{
88 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
89 if value.type_of().is_void() {
90 Ok(None)
91 } else {
92 T::from_js(ctx, value).map(Some)
93 }
94 }
95}
96
97impl<'js, T> FromJs<'js> for Result<T>
99where
100 T: FromJs<'js>,
101{
102 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
105 unsafe {
106 match ctx.handle_exception(value.into_js_value()) {
107 Ok(val) => T::from_js(ctx, Value::from_js_value(ctx.clone(), val)).map(Ok),
108 Err(error) => Ok(Err(error)),
109 }
110 }
111 }
112}
113
114#[cfg(feature = "either")]
116#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "either")))]
117impl<'js, L, R> FromJs<'js> for Either<L, R>
118where
119 L: FromJs<'js>,
120 R: FromJs<'js>,
121{
122 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
123 L::from_js(ctx, value.clone()).map(Left).or_else(|error| {
124 if error.is_from_js() {
125 R::from_js(ctx, value).map(Right)
126 } else {
127 Err(error)
128 }
129 })
130 }
131}
132
133fn tuple_match_size(actual: usize, expected: usize) -> Result<()> {
134 if actual == expected {
135 Ok(())
136 } else {
137 Err(Error::new_from_js_message(
138 "array",
139 "tuple",
140 if actual < expected {
141 "Not enough values"
142 } else {
143 "Too many values"
144 },
145 ))
146 }
147}
148
149fn number_match_range<T: PartialOrd>(
150 val: T,
151 min: T,
152 max: T,
153 from: &'static str,
154 to: &'static str,
155) -> Result<()> {
156 if val < min {
157 Err(Error::new_from_js_message(from, to, "Underflow"))
158 } else if val > max {
159 Err(Error::new_from_js_message(from, to, "Overflow"))
160 } else {
161 Ok(())
162 }
163}
164
165macro_rules! from_js_impls {
166 (ref: $($(#[$meta:meta])* $type:ident,)*) => {
168 $(
169 $(#[$meta])*
170 impl<'js, T> FromJs<'js> for $type<T>
171 where
172 T: FromJs<'js>,
173 {
174 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
175 T::from_js(ctx, value).map($type::new)
176 }
177 }
178 )*
179 };
180
181 (tup: $($($type:ident)*,)*) => {
183 $(
184 impl<'js, $($type,)*> FromJs<'js> for List<($($type,)*)>
185 where
186 $($type: FromJs<'js>,)*
187 {
188 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
189 let array = Array::from_value(value)?;
190
191 let tuple_len = 0 $(+ from_js_impls!(@one $type))*;
192 let array_len = array.len();
193 tuple_match_size(array_len, tuple_len)?;
194
195 Ok(List((
196 $(array.get::<$type>(from_js_impls!(@idx $type))?,)*
197 )))
198 }
199 }
200 )*
201 };
202
203 (list: $($(#[$meta:meta])* $type:ident $({$param:ident: $($pguard:tt)*})* $(($($guard:tt)*))*,)*) => {
205 $(
206 $(#[$meta])*
207 impl<'js, T $(,$param)*> FromJs<'js> for $type<T $(,$param)*>
208 where
209 T: FromJs<'js> $(+ $($guard)*)*,
210 $($param: $($pguard)*,)*
211 {
212 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
213 let array = Array::from_value(value)?;
214 array.iter().collect::<Result<_>>()
215 }
216 }
217 )*
218 };
219
220 (map: $($(#[$meta:meta])* $type:ident $({$param:ident: $($pguard:tt)*})* $(($($guard:tt)*))*,)*) => {
222 $(
223 $(#[$meta])*
224 impl<'js, K, V $(,$param)*> FromJs<'js> for $type<K, V $(,$param)*>
225 where
226 K: FromAtom<'js> $(+ $($guard)*)*,
227 V: FromJs<'js>,
228 $($param: $($pguard)*,)*
229 {
230 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
231 let object = Object::from_value(value)?;
232 object.props().collect::<Result<_>>()
233 }
234 }
235 )*
236 };
237
238 (val: $($type:ty => $($jstype:ident $getfn:ident)*,)*) => {
241 $(
242 impl<'js> FromJs<'js> for $type {
243 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
244 let type_ = value.type_of();
245 match type_ {
246 $(Type::$jstype => Ok(unsafe { value.$getfn() } as _),)*
247 _ => Err(Error::new_from_js(type_.as_str(), stringify!($type))),
248 }
249 }
250 }
251 )*
252 };
253
254 (val: $($base:ident: $($type:ident)*,)*) => {
256 $(
257 $(
258 impl<'js> FromJs<'js> for $type {
259 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
260 let num = <$base>::from_js(ctx, value)?;
261 number_match_range(num, $type::MIN as $base, $type::MAX as $base, stringify!($base), stringify!($type))?;
262 Ok(num as $type)
263 }
264 }
265 )*
266 )*
267 };
268
269 (@one $($t:tt)*) => { 1 };
270
271 (@idx A) => { 0 };
272 (@idx B) => { 1 };
273 (@idx C) => { 2 };
274 (@idx D) => { 3 };
275 (@idx E) => { 4 };
276 (@idx F) => { 5 };
277 (@idx G) => { 6 };
278 (@idx H) => { 7 };
279 (@idx I) => { 8 };
280 (@idx J) => { 9 };
281 (@idx K) => { 10 };
282 (@idx L) => { 11 };
283 (@idx M) => { 12 };
284 (@idx N) => { 13 };
285 (@idx O) => { 14 };
286 (@idx P) => { 15 };
287}
288
289from_js_impls! {
290 val:
291 i32: i8 u8 i16 u16,
292 f64: u32 u64 i64 usize isize,
293}
294
295from_js_impls! {
296 val:
297 bool => Bool get_bool,
298 i32 => Float get_float Int get_int,
299 f64 => Float get_float Int get_int,
300}
301
302from_js_impls! {
303 ref:
304 Box,
305 Rc,
306 Arc,
307 Cell,
308 RefCell,
309 #[cfg(feature = "std")]
310 Mutex,
311 #[cfg(feature = "std")]
312 RwLock,
313}
314
315from_js_impls! {
316 tup:
317 A,
318 A B,
319 A B C,
320 A B C D,
321 A B C D E,
322 A B C D E F,
323 A B C D E F G,
324 A B C D E F G H,
325 A B C D E F G H I,
326 A B C D E F G H I J,
327 A B C D E F G H I J K,
328 A B C D E F G H I J K L,
329 A B C D E F G H I J K L M,
330 A B C D E F G H I J K L M N,
331 A B C D E F G H I J K L M N O,
332 A B C D E F G H I J K L M N O P,
333}
334
335from_js_impls! {
336 list:
337 Vec,
339 VecDeque,
341 LinkedList,
343 #[cfg(feature = "std")]
345 HashSet {S: Default + BuildHasher} (Eq + Hash),
346 HashbrownSet {S: Default + BuildHasher} (Eq + Hash),
348 BTreeSet (Eq + Ord),
350 #[cfg(feature = "indexmap")]
352 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "indexmap")))]
353 IndexSet {S: Default + BuildHasher} (Eq + Hash),
354}
355
356from_js_impls! {
357 map:
358 #[cfg(feature = "std")]
360 HashMap {S: Default + BuildHasher} (Eq + Hash),
361 HashbrownMap {S: Default + BuildHasher} (Eq + Hash),
363 BTreeMap (Eq + Ord),
365 #[cfg(feature = "indexmap")]
367 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "indexmap")))]
368 IndexMap {S: Default + BuildHasher} (Eq + Hash),
369}
370
371impl<'js> FromJs<'js> for f32 {
372 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
373 f64::from_js(ctx, value).map(|value| value as _)
374 }
375}
376
377#[allow(dead_code)]
378fn date_to_millis<'js>(ctx: &Ctx<'js>, value: Value<'js>) -> Result<i64> {
379 let global = ctx.globals();
380 let date_ctor: Object = global.get("Date")?;
381
382 let value = Object::from_value(value)?;
383
384 if !value.is_instance_of(&date_ctor) {
385 return Err(Error::new_from_js("Object", "Date"));
386 }
387
388 let get_time_fn: crate::Function = value.get("getTime")?;
389
390 let millis: Value = get_time_fn.call((crate::function::This(value),))?;
391 if millis.as_float().is_some_and(f64::is_nan) {
392 return Err(Error::new_from_js_message("Date", "i64", "Invalid Date"));
393 }
394 i64::from_js(ctx, millis)
395}
396
397#[cfg(feature = "std")]
398impl<'js> FromJs<'js> for SystemTime {
399 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<SystemTime> {
400 let millis = date_to_millis(ctx, value)?;
401
402 if millis >= 0 {
403 SystemTime::UNIX_EPOCH
405 .checked_add(Duration::from_millis(millis as _))
406 .ok_or_else(|| {
407 Error::new_from_js_message("Date", "SystemTime", "Timestamp too big")
408 })
409 } else {
410 SystemTime::UNIX_EPOCH
412 .checked_sub(Duration::from_millis((-millis) as _))
413 .ok_or_else(|| {
414 Error::new_from_js_message("Date", "SystemTime", "Timestamp too small")
415 })
416 }
417 }
418}
419
420macro_rules! chrono_from_js_impls {
421 ($($type:ident;)+) => {
422 $(
423 #[cfg(feature = "chrono")]
424 impl<'js> FromJs<'js> for chrono::DateTime<chrono::$type> {
425 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<chrono::DateTime<chrono::$type>> {
426 use chrono::TimeZone;
427
428 let millis = date_to_millis(ctx, value)?;
429
430 chrono::$type.timestamp_millis_opt(millis).single()
431 .ok_or_else(|| {
432 Error::new_from_js_message("Date", "chrono::DateTime", "Invalid timestamp")
433 })
434 }
435 }
436 )+
437 };
438}
439
440chrono_from_js_impls! {
441 Utc;
442 Local;
443}
444
445#[cfg(test)]
446mod test {
447 #[test]
448 fn js_to_system_time() {
449 use crate::{Context, Runtime};
450 use std::time::{Duration, SystemTime};
451
452 let runtime = Runtime::new().unwrap();
453 let ctx = Context::full(&runtime).unwrap();
454
455 ctx.with(|ctx| {
456 let res: SystemTime = ctx.eval("new Date(123456789)").unwrap();
457 assert_eq!(
458 Duration::from_millis(123456789),
459 res.duration_since(SystemTime::UNIX_EPOCH).unwrap()
460 );
461
462 assert!(ctx.eval::<SystemTime, _>("new Date(NaN)").is_err());
463
464 #[cfg(not(target_arch = "wasm32"))]
465 {
466 let res: SystemTime = ctx.eval("new Date(-123456789)").unwrap();
467 assert_eq!(
468 Duration::from_millis(123456789),
469 SystemTime::UNIX_EPOCH.duration_since(res).unwrap()
470 );
471 }
472
473 #[cfg(target_arch = "wasm32")]
476 {
477 let res = ctx.eval::<SystemTime, &str>("new Date(-123456789)");
478 match res {
479 Ok(date) => {
480 assert_eq!(
481 Duration::from_millis(123456789),
482 SystemTime::UNIX_EPOCH.duration_since(date).unwrap()
483 );
484 }
485 Err(e) => assert_eq!(
486 "Error converting from js 'Date' into type 'SystemTime': Timestamp too small",
487 e.to_string()
488 ),
489 };
490 }
491 });
492 }
493
494 #[cfg(feature = "chrono")]
495 #[test]
496 fn js_to_chrono() {
497 use crate::{Context, Runtime};
498 use chrono::{DateTime, Utc};
499
500 let runtime = Runtime::new().unwrap();
501 let ctx = Context::full(&runtime).unwrap();
502
503 ctx.with(|ctx| {
504 let res: DateTime<Utc> = ctx.eval("new Date(123456789)").unwrap();
505 assert_eq!(123456789, res.timestamp_millis());
506 });
507
508 ctx.with(|ctx| {
509 let res: DateTime<Utc> = ctx
510 .eval("new Date('Fri Jun 03 2022 23:16:50 GMT+0300')")
511 .unwrap();
512 assert_eq!(1654287410000, res.timestamp_millis());
513 });
514
515 ctx.with(|ctx| {
516 let res: DateTime<Utc> = ctx
517 .eval("new Date('Fri Jun 03 2022 23:16:50 GMT-0300')")
518 .unwrap();
519 assert_eq!(1654309010000, res.timestamp_millis());
520 });
521
522 ctx.with(|ctx| {
523 assert!(ctx.eval::<DateTime<Utc>, _>("new Date(NaN)").is_err());
524 });
525 }
526}