1use crate::host::{fmt_number, with_host, JsObj};
17use fusevm::Value;
18use indexmap::IndexMap;
19
20pub const STATIC_METHODS: &[&str] = &["from", "of", "isView"];
21
22pub const UINT8_STATIC_METHODS: &[&str] = &["from", "of", "isView", "fromBase64", "fromHex"];
25
26pub const UINT8_PROTOTYPE_METHODS: &[&str] = &["toBase64", "setFromBase64", "toHex", "setFromHex"];
29
30pub fn static_methods(kind: &str) -> &'static [&'static str] {
32 if kind == "Uint8Array" {
33 UINT8_STATIC_METHODS
34 } else {
35 STATIC_METHODS
36 }
37}
38
39pub const PROTOTYPE_METHODS: &[&str] = &[
44 "at",
45 "copyWithin",
46 "entries",
47 "every",
48 "fill",
49 "filter",
50 "find",
51 "findIndex",
52 "findLast",
53 "findLastIndex",
54 "forEach",
55 "includes",
56 "indexOf",
57 "join",
58 "keys",
59 "lastIndexOf",
60 "map",
61 "reduce",
62 "reduceRight",
63 "reverse",
64 "set",
65 "slice",
66 "some",
67 "sort",
68 "subarray",
69 "toReversed",
70 "toSorted",
71 "toString",
72 "values",
73 "with",
74];
75
76pub fn is_ctor(name: &str) -> bool {
78 ELEMENT_KINDS.contains(&name) || matches!(name, "ArrayBuffer" | "DataView")
79}
80
81pub const ELEMENT_KINDS: &[&str] = &[
90 "Uint8Array",
91 "Int8Array",
92 "Uint8ClampedArray",
93 "Int16Array",
94 "Uint16Array",
95 "Int32Array",
96 "Uint32Array",
97 "Float32Array",
98 "Float64Array",
99 "BigInt64Array",
101 "BigUint64Array",
102];
103
104pub fn bytes_per_element(kind: &str) -> usize {
106 match kind {
107 "Int8Array" | "Uint8Array" | "Uint8ClampedArray" => 1,
108 "Int16Array" | "Uint16Array" => 2,
109 "Int32Array" | "Uint32Array" | "Float32Array" => 4,
110 "Float64Array" | "BigInt64Array" | "BigUint64Array" => 8,
111 _ => 1,
112 }
113}
114
115fn coerce(kind: &str, n: f64) -> f64 {
118 let wrapped = if n.is_finite() {
122 n.trunc().rem_euclid(4_294_967_296.0) as u32
123 } else {
124 0
125 };
126 match kind {
127 "Int8Array" => (wrapped as u8 as i8) as f64,
128 "Uint8Array" => (wrapped as u8) as f64,
129 "Uint8ClampedArray" => {
130 if n.is_nan() {
131 0.0
132 } else {
133 n.clamp(0.0, 255.0).round_ties_even()
135 }
136 }
137 "Int16Array" => (wrapped as u16 as i16) as f64,
138 "Uint16Array" => (wrapped as u16) as f64,
139 "Int32Array" => (wrapped as i32) as f64,
140 "Uint32Array" => wrapped as f64,
141 "Float32Array" => n as f32 as f64,
142 _ => n, }
144}
145
146pub fn is_bigint_kind(kind: &str) -> bool {
150 matches!(kind, "BigInt64Array" | "BigUint64Array")
151}
152
153fn coerce_val(kind: &str, v: &Value) -> Result<Value, String> {
157 if !is_bigint_kind(kind) {
158 return Ok(Value::Float(coerce(kind, crate::host::to_number_value(v)?)));
159 }
160 let big = crate::builtins::to_bigint(v)?;
166 Ok(with_host(|h| h.new_bigint(wrap_bigint(kind, big))))
167}
168
169fn wrap_bigint(kind: &str, b: num_bigint::BigInt) -> num_bigint::BigInt {
172 use num_traits::cast::ToPrimitive;
173 let modulus = num_bigint::BigInt::from(1u128 << 64);
174 let mut m = b % &modulus;
175 if m.sign() == num_bigint::Sign::Minus {
176 m += &modulus;
177 }
178 let raw = m.to_u64().unwrap_or(0);
180 if kind == "BigInt64Array" {
181 num_bigint::BigInt::from(raw as i64)
182 } else {
183 num_bigint::BigInt::from(raw)
184 }
185}
186
187fn bigint_of(v: &Value) -> num_bigint::BigInt {
190 with_host(|h| match h.get(v) {
191 Some(JsObj::BigInt(b)) => b.clone(),
192 _ => num_bigint::BigInt::from(0),
193 })
194}
195
196fn same_element(stored: &Value, needle: &Value, nan_matches: bool) -> bool {
204 if nan_matches {
205 if let (Value::Float(a), Value::Float(b)) = (stored, needle) {
206 if a.is_nan() && b.is_nan() {
207 return true;
208 }
209 }
210 }
211 with_host(|h| h.strict_eq(stored, needle))
212}
213
214fn zero_of(kind: &str) -> Value {
216 if is_bigint_kind(kind) {
217 with_host(|h| h.new_bigint(num_bigint::BigInt::from(0)))
218 } else {
219 Value::Float(0.0)
220 }
221}
222
223fn num(v: &Value) -> f64 {
227 with_host(|h| h.to_number(v))
228}
229
230pub fn elem_values(v: &Value) -> Vec<Value> {
234 let Some(tag) = super::native_tag(v) else {
235 return Vec::new();
236 };
237 if tag == "TypedArray" {
238 let kind = kind_of(v);
239 let bpe = bytes_per_element(&kind);
240 return (0..view_len(v))
241 .map(|i| {
242 view_bytes(v, i * bpe, bpe)
243 .map(|b| decode(&kind, &b))
244 .unwrap_or(Value::Undef)
245 })
246 .collect();
247 }
248 if tag != "Buffer" {
249 return Vec::new();
250 }
251 with_host(|h| match h.get(v) {
252 Some(JsObj::Object(p)) => super::buffer::window_bytes_h(h, p)
253 .into_iter()
254 .map(|b| Value::Float(b as f64))
255 .collect(),
256 _ => Vec::new(),
257 })
258}
259
260fn make(kind: &str, elems: Vec<Value>) -> Value {
262 let bpe = bytes_per_element(kind);
263 let len = elems.len();
264 let buf = new_array_buffer(len * bpe);
265 let view = make_view(kind, &buf, 0, len);
266 for (i, e) in elems.iter().enumerate() {
267 write_view_bytes(&view, i * bpe, &encode(kind, e));
268 }
269 view
270}
271
272fn make_view(kind: &str, buf: &Value, byte_off: usize, len: usize) -> Value {
274 with_host(|h| {
275 let bpe = bytes_per_element(kind);
276 let mut m = IndexMap::new();
277 m.insert("@@native".into(), h.new_str("TypedArray"));
278 m.insert("@@kind".into(), h.new_str(kind));
279 m.insert("@@buffer".into(), buf.clone());
280 m.insert("buffer".into(), buf.clone());
283 m.insert("length".into(), Value::Float(len as f64));
284 m.insert("byteLength".into(), Value::Float((len * bpe) as f64));
285 m.insert("byteOffset".into(), Value::Float(byte_off as f64));
290 m.insert("BYTES_PER_ELEMENT".into(), Value::Float(bpe as f64));
291 let obj = h.new_object(m);
292 h.ensure_native_protos();
298 if let Some(p) = h.native_proto(kind) {
299 h.set_proto(&obj, p);
300 }
301 for k in [
303 "buffer",
304 "length",
305 "byteLength",
306 "byteOffset",
307 "BYTES_PER_ELEMENT",
308 ] {
309 h.hide_prop(&obj, k);
310 }
311 obj
312 })
313}
314
315fn integer_or_infinity(n: f64) -> f64 {
317 if n.is_nan() {
318 0.0
319 } else {
320 n.trunc() + 0.0
321 }
322}
323
324fn to_index(n: f64) -> Option<usize> {
326 let i = integer_or_infinity(n);
327 (0.0..=9_007_199_254_740_991.0)
328 .contains(&i)
329 .then_some(i as usize)
330}
331
332fn is_primitive(v: &Value) -> bool {
334 match v {
335 Value::Obj(_) => with_host(|h| {
336 matches!(
337 h.get(v),
338 Some(JsObj::Str(_))
339 | Some(JsObj::Null)
340 | Some(JsObj::BigInt(_))
341 | Some(JsObj::Symbol { .. })
342 )
343 }),
344 _ => true,
345 }
346}
347
348pub fn construct(kind: &str, args: &[Value]) -> Result<Value, String> {
351 if kind == "ArrayBuffer" {
352 let n = to_index(super::arg_num(args, 0))
353 .ok_or_else(|| crate::host::range_error("Invalid array buffer length"))?;
354 let max = match args.get(1) {
356 Some(opts) => {
357 crate::builtins::get_property(opts, "maxByteLength").unwrap_or(Value::Undef)
358 }
359 None => Value::Undef,
360 };
361 let max_len = match max {
362 Value::Undef => None,
363 _ => match to_index(with_host(|h| h.to_number(&max))) {
364 Some(m) if m >= n => Some(m),
365 _ => return Err(crate::host::range_error("Invalid array buffer max length")),
366 },
367 };
368 let ab = new_array_buffer(n);
369 if let Some(m) = max_len {
372 with_host(|h| {
373 if let Some(JsObj::Object(p)) = h.get_mut(&ab) {
374 p.insert("@@maxByteLength".into(), Value::Float(m as f64));
375 p.insert("maxByteLength".into(), Value::Float(m as f64));
376 p.insert("resizable".into(), Value::Bool(true));
377 }
378 h.hide_prop(&ab, "maxByteLength");
379 h.hide_prop(&ab, "resizable");
380 });
381 }
382 return Ok(ab);
383 }
384 if let Some(first) = args.first() {
389 if super::native_tag(first).as_deref() == Some("ArrayBuffer") {
390 if is_detached(first) {
392 return Err(crate::host::type_error(
393 "Cannot perform Construct on a detached ArrayBuffer",
394 ));
395 }
396 let bpe = bytes_per_element(kind);
399 let total = buffer_byte_length(first);
400 let off_n = super::arg_num(args, 1);
401 let off = to_index(off_n).ok_or_else(|| {
402 crate::host::range_error(&format!(
403 "Start offset {} is outside the bounds of the buffer",
404 fmt_number(off_n)
405 ))
406 })?;
407 if off % bpe != 0 {
408 return Err(crate::host::range_error(&format!(
409 "start offset of {kind} should be a multiple of {bpe}"
410 )));
411 }
412 let len = match args.get(2) {
413 Some(Value::Undef) | None => {
414 if total % bpe != 0 {
415 return Err(crate::host::range_error(&format!(
416 "byte length of {kind} should be a multiple of {bpe}"
417 )));
418 }
419 if off > total {
420 return Err(crate::host::range_error(&format!(
421 "Start offset {off} is outside the bounds of the buffer"
422 )));
423 }
424 (total - off) / bpe
425 }
426 Some(_) => {
427 let len_n = super::arg_num(args, 2);
428 let bad = || {
429 crate::host::range_error(&format!(
430 "Invalid typed array length: {}",
431 fmt_number(len_n)
432 ))
433 };
434 let len = to_index(len_n).ok_or_else(bad)?;
435 if off + len * bpe > total {
436 return Err(bad());
437 }
438 len
439 }
440 };
441 return Ok(make_view(kind, first, off, len));
442 }
443 }
444 let elems = build_elems(kind, args)?;
445 Ok(make(kind, elems))
446}
447
448pub const DATAVIEW_METHODS: &[&str] = &[
450 "getInt8",
451 "getUint8",
452 "getInt16",
453 "getUint16",
454 "getInt32",
455 "getUint32",
456 "getFloat32",
457 "getFloat64",
458 "getBigInt64",
459 "getBigUint64",
460 "setInt8",
461 "setUint8",
462 "setInt16",
463 "setUint16",
464 "setInt32",
465 "setUint32",
466 "setFloat32",
467 "setFloat64",
468 "setBigInt64",
469 "setBigUint64",
470];
471
472pub fn construct_dataview(args: &[Value]) -> Result<Value, String> {
474 let buf = args.first().cloned().unwrap_or(Value::Undef);
475 if super::native_tag(&buf).as_deref() != Some("ArrayBuffer") {
476 return Err(crate::host::type_error(
477 "First argument to DataView constructor must be an ArrayBuffer",
478 ));
479 }
480 let total = buffer_byte_length(&buf);
483 let off_n = super::arg_num(args, 1);
484 let outside = |n: f64| {
485 crate::host::range_error(&format!(
486 "Start offset {} is outside the bounds of the buffer",
487 fmt_number(integer_or_infinity(n))
488 ))
489 };
490 let off = to_index(off_n).ok_or_else(|| outside(off_n))?;
491 if off > total {
492 return Err(outside(off_n));
493 }
494 let bad_len = |n: f64| {
495 crate::host::range_error(&format!(
496 "Invalid DataView length {}",
497 fmt_number(integer_or_infinity(n))
498 ))
499 };
500 let len = match args.get(2) {
501 Some(Value::Undef) | None => total - off,
502 Some(_) => {
503 let len_n = super::arg_num(args, 2);
504 let len = to_index(len_n).ok_or_else(|| bad_len(len_n))?;
505 if off + len > total {
506 return Err(bad_len(len_n));
507 }
508 len
509 }
510 };
511 Ok(with_host(|h| {
512 let mut m = IndexMap::new();
513 m.insert("@@native".into(), h.new_str("DataView"));
514 m.insert("@@buffer".into(), buf.clone());
515 m.insert("buffer".into(), buf.clone());
516 m.insert("byteOffset".into(), Value::Float(off as f64));
517 m.insert("byteLength".into(), Value::Float(len as f64));
518 let obj = h.new_object(m);
519 for k in ["buffer", "byteOffset", "byteLength"] {
520 h.hide_prop(&obj, k);
521 }
522 h.ensure_native_protos();
523 if let Some(p) = h.ensure_ctor_proto("DataView") {
524 h.set_proto(&obj, p);
525 }
526 obj
527 }))
528}
529
530pub fn dataview_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
533 if view_detached(recv) {
534 return Err(detached_error("DataView.prototype", method, false));
535 }
536 let Some(spec) = method.get(3..) else {
537 return Err(crate::host::type_error(&format!(
538 "{method} is not a function"
539 )));
540 };
541 let width = match spec {
542 "Int8" | "Uint8" => 1,
543 "Int16" | "Uint16" => 2,
544 "Int32" | "Uint32" | "Float32" => 4,
545 "Float64" | "BigInt64" | "BigUint64" => 8,
546 _ => {
547 return Err(crate::host::type_error(&format!(
548 "{method} is not a function"
549 )))
550 }
551 };
552 let is_get = method.starts_with("get");
553 let requested = super::arg_num(args, 0);
558 let requested = if requested.is_nan() {
559 0.0
560 } else {
561 requested.trunc()
562 };
563 let span = with_host(|h| match h.get(recv) {
564 Some(JsObj::Object(p)) => p.get("byteLength").map(|l| h.to_number(l)).unwrap_or(0.0),
565 _ => 0.0,
566 });
567 if requested < 0.0 || requested + width as f64 > span {
568 return Err(crate::host::range_error(
569 "Offset is outside the bounds of the DataView",
570 ));
571 }
572 let at = requested as usize;
573 let le = with_host(|h| {
576 h.truthy(
577 args.get(if is_get { 1 } else { 2 })
578 .unwrap_or(&Value::Undef),
579 )
580 });
581 if is_get {
582 let mut b = view_bytes(recv, at, width).unwrap_or_else(|| vec![0; width]);
583 if !le {
584 b.reverse();
585 }
586 return Ok(match spec {
587 "Int8" => Value::Float(b[0] as i8 as f64),
588 "Uint8" => Value::Float(b[0] as f64),
589 "Int16" => Value::Float(i16::from_le_bytes([b[0], b[1]]) as f64),
590 "Uint16" => Value::Float(u16::from_le_bytes([b[0], b[1]]) as f64),
591 "Int32" => Value::Float(i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
592 "Uint32" => Value::Float(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
593 "Float32" => Value::Float(f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
594 "Float64" => Value::Float(f64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]))),
595 "BigInt64" => {
596 let raw = i64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
597 with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
598 }
599 _ => {
600 let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
601 with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
602 }
603 });
604 }
605 let val = args.get(1).cloned().unwrap_or(Value::Undef);
606 let mut b = match spec {
607 "BigInt64" | "BigUint64" => {
608 use num_traits::cast::ToPrimitive;
609 let big = crate::builtins::to_bigint(&val)?;
612 let raw = if spec == "BigInt64" {
613 big.to_i64().unwrap_or(0) as u64
614 } else {
615 big.to_u64().unwrap_or(0)
616 };
617 raw.to_le_bytes().to_vec()
618 }
619 _ => {
620 let n = with_host(|h| h.to_number(&val));
621 match spec {
622 "Int8" | "Uint8" => vec![n as i64 as u8],
623 "Int16" | "Uint16" => (n as i64 as u16).to_le_bytes().to_vec(),
624 "Int32" | "Uint32" => (n as i64 as u32).to_le_bytes().to_vec(),
625 "Float32" => (n as f32).to_le_bytes().to_vec(),
626 _ => n.to_le_bytes().to_vec(),
627 }
628 }
629 };
630 if !le {
631 b.reverse();
632 }
633 write_view_bytes(recv, at, &b);
634 Ok(Value::Undef)
635}
636
637pub fn buffer_resize(ab: &Value, args: &[Value]) -> Result<Value, String> {
640 let max = with_host(|h| match h.get(ab) {
641 Some(JsObj::Object(p)) => p.get("@@maxByteLength").map(|m| h.to_number(m) as usize),
642 _ => None,
643 })
644 .ok_or_else(|| {
645 crate::host::type_error(
646 "ArrayBuffer.prototype.resize called on a non-resizable ArrayBuffer",
647 )
648 })?;
649 let n = super::arg_num(args, 0).max(0.0) as usize;
650 if n > max {
651 return Err(crate::host::range_error("Invalid array buffer length"));
652 }
653 let store = store_of(ab);
654 with_host(|h| {
655 if let Some(a) = store {
656 if let Some(JsObj::Array(items)) = h.get_mut(&a) {
657 items.resize(n, Value::Float(0.0));
658 }
659 }
660 if let Some(JsObj::Object(p)) = h.get_mut(ab) {
661 p.insert("byteLength".into(), Value::Float(n as f64));
662 }
663 });
664 Ok(Value::Undef)
665}
666
667pub fn write_buffer_bytes(ab: &Value, bytes: &[u8]) {
670 let Some(store) = store_of(ab) else { return };
671 with_host(|h| {
672 if let Some(JsObj::Array(items)) = h.get_mut(&store) {
673 *items = bytes.iter().map(|b| Value::Float(*b as f64)).collect();
674 }
675 if let Some(JsObj::Object(p)) = h.get_mut(ab) {
676 p.insert("byteLength".into(), Value::Float(bytes.len() as f64));
677 }
678 });
679}
680
681pub fn buffer_store(ab: &Value) -> Option<Value> {
684 store_of(ab)
685}
686
687pub fn buffer_bytes_snapshot(ab: &Value) -> Option<Vec<u8>> {
689 let store = store_of(ab)?;
690 with_host(|h| match h.get(&store) {
691 Some(JsObj::Array(items)) => {
692 Some(items.iter().map(|x| h.to_number(x) as i64 as u8).collect())
693 }
694 _ => None,
695 })
696}
697
698pub fn buffer_byte_length(ab: &Value) -> usize {
700 with_host(|h| match h.get(ab) {
701 Some(JsObj::Object(p)) => match p.get("@@bytes").and_then(|a| h.get(a)) {
702 Some(JsObj::Array(items)) => items.len(),
703 _ => 0,
704 },
705 _ => 0,
706 })
707}
708
709pub fn buffer_slice(ab: &Value, args: &[Value]) -> Value {
712 let total = buffer_byte_length(ab) as i64;
713 let idx = |v: Option<&Value>, dflt: i64| -> usize {
714 let n = match v {
715 None | Some(Value::Undef) => dflt,
716 Some(x) => with_host(|h| h.to_number(x)) as i64,
717 };
718 (if n < 0 { total + n } else { n }).clamp(0, total) as usize
719 };
720 let start = idx(args.first(), 0);
721 let end = idx(args.get(1), total).max(start);
722 let out = new_array_buffer(end - start);
723 let src = with_host(|h| match h.get(ab) {
724 Some(JsObj::Object(p)) => match p.get("@@bytes").and_then(|a| h.get(a)) {
725 Some(JsObj::Array(items)) => items[start..end].to_vec(),
726 _ => Vec::new(),
727 },
728 _ => Vec::new(),
729 });
730 with_host(|h| {
731 if let Some(JsObj::Object(p)) = h.get(&out) {
732 if let Some(arr) = p.get("@@bytes").cloned() {
733 if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
734 *items = src;
735 }
736 }
737 }
738 });
739 out
740}
741
742fn build_elems(kind: &str, args: &[Value]) -> Result<Vec<Value>, String> {
746 match args.first() {
747 None | Some(Value::Undef) => Ok(Vec::new()),
748 Some(v) if is_primitive(v) => {
752 let n_raw = super::arg_num(args, 0);
753 let n = to_index(n_raw).ok_or_else(|| {
754 crate::host::range_error(&format!(
755 "Invalid typed array length: {}",
756 fmt_number(n_raw)
757 ))
758 })?;
759 Ok(vec![zero_of(kind); n])
760 }
761 Some(v) => {
762 let items = match super::native_tag(v).as_deref() {
765 Some("TypedArray") | Some("Buffer") => elem_values(v),
766 _ if crate::builtins::get_property(v, "@@iterator")
769 .map_or(true, |m| !matches!(m, Value::Undef)) =>
770 {
771 crate::host::iter_all(v).unwrap_or_default()
772 }
773 _ => {
774 let len = crate::builtins::get_property(v, "length")?;
775 let n = with_host(|h| h.to_number(&len));
776 let n = if n.is_finite() && n > 0.0 {
777 n as usize
778 } else {
779 0
780 };
781 (0..n)
782 .map(|i| crate::builtins::get_property(v, &i.to_string()))
783 .collect::<Result<Vec<_>, _>>()?
784 }
785 };
786 items.iter().map(|x| coerce_val(kind, x)).collect()
787 }
788 }
789}
790
791#[derive(Clone, Copy, PartialEq)]
796enum LastChunk {
797 Loose,
798 Strict,
799 StopBeforePartial,
800}
801
802fn base64_options(opt: Option<&Value>) -> Result<(bool, LastChunk), String> {
806 let Some(o) = opt.filter(|v| !matches!(v, Value::Undef)) else {
807 return Ok((false, LastChunk::Loose));
808 };
809 if !with_host(|h| matches!(h.get(o), Some(JsObj::Object(_)))) {
810 return Err(crate::host::type_error("invalid_argument"));
811 }
812 let read = |k: &str| {
813 with_host(|h| match h.get(o) {
814 Some(JsObj::Object(p)) => p.get(k).filter(|v| !matches!(v, Value::Undef)).cloned(),
815 _ => None,
816 })
817 };
818 let url = match read("alphabet") {
819 None => false,
820 Some(v) => match with_host(|h| h.str_of(&v)).as_str() {
821 "base64" => false,
822 "base64url" => true,
823 other => return Err(crate::host::type_error(&format!("invalid option {other}"))),
824 },
825 };
826 let last = match read("lastChunkHandling") {
827 None => LastChunk::Loose,
828 Some(v) => match with_host(|h| h.str_of(&v)).as_str() {
829 "loose" => LastChunk::Loose,
830 "strict" => LastChunk::Strict,
831 "stop-before-partial" => LastChunk::StopBeforePartial,
832 other => return Err(crate::host::type_error(&format!("invalid option {other}"))),
833 },
834 };
835 Ok((url, last))
836}
837
838const B64_BAD: &str =
839 "SyntaxError: Found a character that cannot be part of a valid base64 string.";
840const B64_SINGLE: &str =
841 "SyntaxError: The base64 input terminates with a single character, excluding padding (=).";
842
843fn decode_base64_strict(s: &str, url: bool, last: LastChunk) -> Result<(Vec<u8>, usize), String> {
850 let value = |c: char| -> Option<u32> {
851 let table = if url {
852 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
853 } else {
854 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
855 };
856 table.find(c).map(|i| i as u32)
857 };
858 let chars: Vec<char> = s.chars().collect();
859 let mut out = Vec::new();
860 let mut chunk: Vec<u32> = Vec::new();
861 let mut consumed = 0usize;
862 let mut i = 0usize;
863 while i < chars.len() {
864 let c = chars[i];
865 if c.is_ascii_whitespace() {
866 i += 1;
867 continue;
868 }
869 if c == '=' {
870 let pads = chars[i..].iter().filter(|c| **c == '=').count();
873 let rest_ok = chars[i..]
874 .iter()
875 .all(|c| *c == '=' || c.is_ascii_whitespace());
876 let want = 4 - chunk.len();
877 if !rest_ok || chunk.len() < 2 || pads != want {
878 return Err(B64_BAD.into());
879 }
880 out.extend(flush_base64_chunk(&chunk));
881 return Ok((out, chars.len()));
882 }
883 let Some(v) = value(c) else {
884 return Err(B64_BAD.into());
885 };
886 chunk.push(v);
887 i += 1;
888 if chunk.len() == 4 {
889 out.extend(flush_base64_chunk(&chunk));
890 chunk.clear();
891 consumed = i;
892 }
893 }
894 match chunk.len() {
895 0 => Ok((out, consumed)),
896 1 if last != LastChunk::StopBeforePartial => Err(B64_SINGLE.into()),
898 _ if last == LastChunk::StopBeforePartial => Ok((out, consumed)),
899 1 => Ok((out, consumed)),
900 _ if last == LastChunk::Strict => Err(B64_SINGLE.into()),
901 _ => {
902 out.extend(flush_base64_chunk(&chunk));
903 Ok((out, chars.len()))
904 }
905 }
906}
907
908fn flush_base64_chunk(chunk: &[u32]) -> Vec<u8> {
910 let mut acc = 0u32;
911 for v in chunk {
912 acc = (acc << 6) | v;
913 }
914 let bytes = chunk.len() - 1;
915 acc <<= 6 * (4 - chunk.len());
916 let all = [(acc >> 16) as u8, (acc >> 8) as u8, acc as u8];
917 all[..bytes].to_vec()
918}
919
920const HEX_BAD: &str = "SyntaxError: Input string must contain hex characters in even length";
921
922fn decode_hex_strict(s: &str) -> Result<Vec<u8>, String> {
925 let chars: Vec<char> = s.chars().collect();
926 if chars.len() % 2 != 0 || !chars.iter().all(|c| c.is_ascii_hexdigit()) {
927 return Err(HEX_BAD.into());
928 }
929 Ok(chars
930 .chunks(2)
931 .map(|p| {
932 let hi = p[0].to_digit(16).expect("checked");
933 let lo = p[1].to_digit(16).expect("checked");
934 (hi * 16 + lo) as u8
935 })
936 .collect())
937}
938
939fn base64_input(args: &[Value]) -> Result<String, String> {
942 let v = args.first().cloned().unwrap_or(Value::Undef);
943 let is_str = matches!(v, Value::Str(_))
944 || with_host(|h| matches!(h.get(&v), Some(crate::host::JsObj::Str(_))));
945 if !is_str {
946 return Err(crate::host::type_error("input argument must be a string"));
947 }
948 Ok(with_host(|h| h.str_of(&v)))
949}
950
951fn from_base64_static(method: &str, args: &[Value]) -> Result<Value, String> {
953 let s = base64_input(args)?;
954 let bytes = if method == "fromHex" {
955 decode_hex_strict(&s)?
956 } else {
957 let (url, last) = base64_options(args.get(1))?;
958 decode_base64_strict(&s, url, last)?.0
959 };
960 Ok(make(
961 "Uint8Array",
962 bytes.iter().map(|b| Value::Float(*b as f64)).collect(),
963 ))
964}
965
966pub fn static_call(kind: &str, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
969 if matches!(method, "fromBase64" | "fromHex") {
971 if kind != "Uint8Array" {
972 return None;
973 }
974 return Some(from_base64_static(method, args));
975 }
976 Some(match method {
977 "of" => args
978 .iter()
979 .map(|x| coerce_val(kind, x))
980 .collect::<Result<Vec<Value>, String>>()
981 .map(|e| make(kind, e)),
982 "from" => from(kind, args),
983 "isView" => Ok(Value::Bool(with_host(|h| {
986 matches!(
987 h.get(&args.first().cloned().unwrap_or(Value::Undef)),
988 Some(crate::host::JsObj::Object(p))
989 if matches!(
990 p.get("@@native").map(|t| h.str_of(t)).as_deref(),
991 Some("TypedArray") | Some("Buffer") | Some("DataView")
992 )
993 )
994 }))),
995 _ => return None,
996 })
997}
998
999fn from(kind: &str, args: &[Value]) -> Result<Value, String> {
1000 let src = args.first().cloned().unwrap_or(Value::Undef);
1001 let map_fn = args
1002 .get(1)
1003 .cloned()
1004 .filter(|f| with_host(|h| crate::host::is_callable(h, f)));
1005 let items = if let Some(e) = elems_of(&src) {
1008 e.into_iter().map(Value::Float).collect()
1009 } else {
1010 crate::host::iter_all(&src).unwrap_or_else(|_| crate::builtins::array_like_items(&src))
1011 };
1012 let mut out = Vec::with_capacity(items.len());
1013 for (i, it) in items.into_iter().enumerate() {
1014 let mapped = match &map_fn {
1015 Some(f) => crate::host::invoke(f, vec![it, Value::Float(i as f64)], None)?,
1016 None => it,
1017 };
1018 out.push(coerce_val(kind, &mapped)?);
1019 }
1020 Ok(make(kind, out))
1021}
1022
1023pub fn elems_of(v: &Value) -> Option<Vec<f64>> {
1025 let tag = super::native_tag(v)?;
1026 if !matches!(tag.as_str(), "TypedArray" | "Buffer") {
1027 return None;
1028 }
1029 let vals = elem_values(v);
1030 Some(with_host(|h| vals.iter().map(|x| h.to_number(x)).collect()))
1031}
1032
1033pub fn index_len(v: &Value) -> Option<usize> {
1042 match super::native_tag(v)?.as_str() {
1043 "TypedArray" => Some(view_len(v)),
1044 "Buffer" => with_host(|h| match h.get(v) {
1045 Some(JsObj::Object(p)) => Some(super::buffer::window_h(h, p).1),
1046 _ => None,
1047 }),
1048 _ => None,
1049 }
1050}
1051
1052pub fn has_index(v: &Value, key: &str) -> Option<bool> {
1055 let len = index_len(v)?;
1056 Some(key.parse::<usize>().map(|i| i < len).unwrap_or(false))
1057}
1058
1059pub fn kind_of(recv: &Value) -> String {
1061 with_host(|h| match h.get(recv) {
1062 Some(JsObj::Object(p)) => p
1063 .get("@@kind")
1064 .map(|v| h.str_of(v))
1065 .unwrap_or_else(|| "Uint8Array".into()),
1066 _ => "Uint8Array".into(),
1067 })
1068}
1069
1070pub fn new_array_buffer(n: usize) -> Value {
1082 let arr = with_host(|h| h.new_array(vec![Value::Float(0.0); n]));
1083 array_buffer_over(arr)
1084}
1085
1086pub fn array_buffer_over(arr: Value) -> Value {
1090 with_host(|h| {
1091 let n = match h.get(&arr) {
1092 Some(JsObj::Array(items)) => items.len(),
1093 _ => 0,
1094 };
1095 let mut m = IndexMap::new();
1096 m.insert("@@native".into(), h.new_str("ArrayBuffer"));
1097 m.insert("@@bytes".into(), arr);
1098 m.insert("byteLength".into(), Value::Float(n as f64));
1099 m.insert("detached".into(), Value::Bool(false));
1103 m.insert("resizable".into(), Value::Bool(false));
1106 m.insert("maxByteLength".into(), Value::Float(n as f64));
1107 let obj = h.new_object(m);
1108 for k in ["byteLength", "detached", "resizable", "maxByteLength"] {
1109 h.hide_prop(&obj, k);
1110 }
1111 if let Some(p) = h.ensure_ctor_proto("ArrayBuffer") {
1114 h.set_proto(&obj, p);
1115 }
1116 obj
1117 })
1118}
1119
1120pub fn is_untransferable(ab: &Value) -> bool {
1124 with_host(|h| matches!(h.get(ab), Some(JsObj::Object(p)) if p.contains_key("@@untransferable")))
1125}
1126
1127pub fn mark_untransferable(ab: &Value) {
1129 with_host(|h| {
1130 if let Some(JsObj::Object(p)) = h.get_mut(ab) {
1131 p.insert("@@untransferable".into(), Value::Bool(true));
1132 }
1133 });
1134}
1135
1136pub fn is_detached(ab: &Value) -> bool {
1142 with_host(|h| match h.get(ab) {
1143 Some(JsObj::Object(p)) => p.get("detached").map(|v| h.truthy(v)).unwrap_or(false),
1144 _ => false,
1145 })
1146}
1147
1148pub fn view_detached(v: &Value) -> bool {
1150 with_host(|h| view_detached_h(h, v))
1151}
1152
1153pub fn view_detached_h(h: &crate::host::JsHost, v: &Value) -> bool {
1156 let buf = match h.get(v) {
1157 Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
1158 _ => None,
1159 };
1160 match buf.and_then(|b| match h.get(&b) {
1161 Some(JsObj::Object(p)) => p.get("detached").cloned(),
1162 _ => None,
1163 }) {
1164 Some(d) => h.truthy(&d),
1165 None => false,
1166 }
1167}
1168
1169pub fn detach_buffer(ab: &Value) {
1172 detach(ab)
1173}
1174
1175fn detach(ab: &Value) {
1176 let store = store_of(ab);
1177 with_host(|h| {
1178 if let Some(JsObj::Array(items)) = store.as_ref().and_then(|s| h.get_mut(s)) {
1181 items.clear();
1182 }
1183 if let Some(JsObj::Object(p)) = h.get_mut(ab) {
1184 p.insert("byteLength".into(), Value::Float(0.0));
1185 p.insert("detached".into(), Value::Bool(true));
1186 }
1187 h.hide_prop(ab, "byteLength");
1188 h.hide_prop(ab, "detached");
1189 });
1190}
1191
1192pub fn buffer_transfer(ab: &Value, args: &[Value], fixed: bool) -> Result<Value, String> {
1198 let method = if fixed {
1199 "transferToFixedLength"
1200 } else {
1201 "transfer"
1202 };
1203 if is_detached(ab) {
1204 return Err(crate::host::type_error(&format!(
1205 "Cannot perform ArrayBuffer.prototype.{method} on a detached ArrayBuffer"
1206 )));
1207 }
1208 if is_untransferable(ab) {
1209 return Err(crate::host::type_error(
1210 "ArrayBuffer is not detachable and could not be cloned.",
1211 ));
1212 }
1213 let old = byte_len_of(ab);
1214 let new_len = match args.first().filter(|v| !matches!(v, Value::Undef)) {
1215 Some(v) => with_host(|h| h.to_number(v)).max(0.0) as usize,
1216 None => old,
1217 };
1218 let mut bytes = view_bytes_of_buffer(ab, old);
1219 bytes.resize(new_len, 0);
1220 let out = new_array_buffer(new_len);
1221 write_buffer_bytes(&out, &bytes);
1222 if !fixed {
1223 let resizable = with_host(|h| match h.get(ab) {
1226 Some(JsObj::Object(p)) => p.contains_key("@@maxByteLength"),
1227 _ => false,
1228 });
1229 if resizable {
1230 let max = with_host(|h| match h.get(ab) {
1231 Some(JsObj::Object(p)) => p.get("@@maxByteLength").cloned(),
1232 _ => None,
1233 });
1234 if let Some(max) = max {
1235 with_host(|h| {
1236 if let Some(JsObj::Object(p)) = h.get_mut(&out) {
1237 p.insert("@@maxByteLength".into(), max);
1238 }
1239 });
1240 }
1241 }
1242 }
1243 detach(ab);
1244 Ok(out)
1245}
1246
1247fn byte_len_of(ab: &Value) -> usize {
1249 with_host(|h| match h.get(ab) {
1250 Some(JsObj::Object(p)) => {
1251 p.get("byteLength").map(|l| h.to_number(l)).unwrap_or(0.0) as usize
1252 }
1253 _ => 0,
1254 })
1255}
1256
1257fn view_bytes_of_buffer(ab: &Value, n: usize) -> Vec<u8> {
1259 let Some(store) = store_of(ab) else {
1260 return Vec::new();
1261 };
1262 with_host(|h| match h.get(&store) {
1263 Some(JsObj::Array(items)) => items
1264 .iter()
1265 .take(n)
1266 .map(|x| h.to_number(x) as i64 as u8)
1267 .collect(),
1268 _ => Vec::new(),
1269 })
1270}
1271
1272pub fn detached_error(label: &str, method: &str, buffer_only: bool) -> String {
1275 let tail = if buffer_only {
1276 "a detached ArrayBuffer"
1277 } else {
1278 "a detached or out-of-bounds ArrayBuffer"
1279 };
1280 let method = match method {
1286 "@@iterator" => "values",
1287 other => other,
1288 };
1289 crate::host::type_error(&format!("Cannot perform {label}.{method} on {tail}"))
1290}
1291
1292fn store_of(ab: &Value) -> Option<Value> {
1294 with_host(|h| match h.get(ab) {
1295 Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
1296 _ => None,
1297 })
1298}
1299
1300fn view_base(v: &Value) -> Option<(Value, usize)> {
1302 with_host(|h| match h.get(v) {
1303 Some(JsObj::Object(p)) => {
1304 let buf = p.get("@@buffer").cloned()?;
1305 let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0);
1306 Some((buf, off.max(0.0) as usize))
1307 }
1308 _ => None,
1309 })
1310}
1311
1312pub fn view_bytes(v: &Value, at: usize, n: usize) -> Option<Vec<u8>> {
1314 let (buf, off) = view_base(v)?;
1315 let store = store_of(&buf)?;
1316 with_host(|h| match h.get(&store) {
1317 Some(JsObj::Array(items)) => {
1318 let start = off + at;
1319 if start + n > items.len() {
1320 return None;
1321 }
1322 Some(
1323 items[start..start + n]
1324 .iter()
1325 .map(|x| h.to_number(x) as i64 as u8)
1326 .collect(),
1327 )
1328 }
1329 _ => None,
1330 })
1331}
1332
1333pub fn write_view_bytes(v: &Value, at: usize, bytes: &[u8]) -> bool {
1336 let Some((buf, off)) = view_base(v) else {
1337 return false;
1338 };
1339 let Some(store) = store_of(&buf) else {
1340 return false;
1341 };
1342 with_host(|h| match h.get_mut(&store) {
1343 Some(JsObj::Array(items)) => {
1344 let start = off + at;
1345 if start + bytes.len() > items.len() {
1346 return false;
1347 }
1348 for (i, b) in bytes.iter().enumerate() {
1349 items[start + i] = Value::Float(*b as f64);
1350 }
1351 true
1352 }
1353 _ => false,
1354 })
1355}
1356
1357fn decode(kind: &str, b: &[u8]) -> Value {
1360 match kind {
1361 "Int8Array" => Value::Float(b[0] as i8 as f64),
1362 "Uint8Array" | "Uint8ClampedArray" => Value::Float(b[0] as f64),
1363 "Int16Array" => Value::Float(i16::from_le_bytes([b[0], b[1]]) as f64),
1364 "Uint16Array" => Value::Float(u16::from_le_bytes([b[0], b[1]]) as f64),
1365 "Int32Array" => Value::Float(i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1366 "Uint32Array" => Value::Float(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1367 "Float32Array" => Value::Float(f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1368 "BigInt64Array" => {
1369 let raw = i64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1370 with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
1371 }
1372 "BigUint64Array" => {
1373 let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1374 with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
1375 }
1376 _ => Value::Float(f64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]))),
1377 }
1378}
1379
1380fn encode(kind: &str, v: &Value) -> Vec<u8> {
1382 if is_bigint_kind(kind) {
1383 use num_traits::cast::ToPrimitive;
1384 let b = bigint_of(v);
1385 let raw = if kind == "BigInt64Array" {
1386 b.to_i64().unwrap_or(0) as u64
1387 } else {
1388 b.to_u64().unwrap_or(0)
1389 };
1390 return raw.to_le_bytes().to_vec();
1391 }
1392 let n = num(v);
1393 match kind {
1394 "Int8Array" => vec![n as i64 as i8 as u8],
1395 "Uint8Array" | "Uint8ClampedArray" => vec![n as i64 as u8],
1396 "Int16Array" => (n as i64 as i16).to_le_bytes().to_vec(),
1397 "Uint16Array" => (n as i64 as u16).to_le_bytes().to_vec(),
1398 "Int32Array" => (n as i64 as i32).to_le_bytes().to_vec(),
1399 "Uint32Array" => (n as i64 as u32).to_le_bytes().to_vec(),
1400 "Float32Array" => (n as f32).to_le_bytes().to_vec(),
1401 _ => n.to_le_bytes().to_vec(),
1402 }
1403}
1404
1405pub fn elems_with_host(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
1410 if let Some(JsObj::Object(p)) = h.get(v) {
1411 if p.contains_key("@@bytes") {
1412 return super::buffer::window_bytes_h(h, p)
1413 .into_iter()
1414 .map(|b| Value::Float(b as f64))
1415 .collect();
1416 }
1417 }
1418 let Some((kind, raws)) = raw_elems(h, v) else {
1419 return Vec::new();
1420 };
1421 if is_bigint_kind(&kind) {
1424 return vec![Value::Undef; raws.len()];
1425 }
1426 raws.iter().map(|b| decode(&kind, b)).collect()
1427}
1428
1429fn raw_elems(h: &crate::host::JsHost, v: &Value) -> Option<(String, Vec<Vec<u8>>)> {
1432 let JsObj::Object(p) = h.get(v)? else {
1433 return None;
1434 };
1435 let kind = p
1436 .get("@@kind")
1437 .map(|k| h.str_of(k))
1438 .unwrap_or_else(|| "Uint8Array".into());
1439 let bpe = bytes_per_element(&kind);
1440 let len = if view_detached_h(h, v) {
1444 0
1445 } else {
1446 p.get("length").map(|l| h.to_number(l)).unwrap_or(0.0) as usize
1447 };
1448 let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0) as usize;
1449 let store = match p.get("@@buffer").and_then(|b| h.get(b)) {
1450 Some(JsObj::Object(bp)) => bp.get("@@bytes").and_then(|a| h.get(a)),
1451 _ => None,
1452 };
1453 let JsObj::Array(bytes) = store? else {
1454 return None;
1455 };
1456 let out = (0..len)
1457 .map(|i| {
1458 let start = off + i * bpe;
1459 if start + bpe > bytes.len() {
1460 return vec![0u8; bpe];
1461 }
1462 bytes[start..start + bpe]
1463 .iter()
1464 .map(|x| h.to_number(x) as i64 as u8)
1465 .collect()
1466 })
1467 .collect();
1468 Some((kind, out))
1469}
1470
1471pub fn elems_mut_host(h: &mut crate::host::JsHost, v: &Value) -> Vec<Value> {
1475 if let Some(JsObj::Object(p)) = h.get(v) {
1476 if p.contains_key("@@bytes") {
1477 return super::buffer::window_bytes_h(h, p)
1478 .into_iter()
1479 .map(|b| Value::Float(b as f64))
1480 .collect();
1481 }
1482 }
1483 let Some((kind, raws)) = raw_elems(h, v) else {
1484 return Vec::new();
1485 };
1486 raws.iter()
1487 .map(|b| {
1488 if !is_bigint_kind(&kind) {
1489 return decode(&kind, b);
1490 }
1491 let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1492 h.new_bigint(if kind == "BigInt64Array" {
1493 num_bigint::BigInt::from(raw as i64)
1494 } else {
1495 num_bigint::BigInt::from(raw)
1496 })
1497 })
1498 .collect()
1499}
1500
1501pub fn elems_display(h: &crate::host::JsHost, v: &Value) -> Vec<String> {
1505 let Some((kind, raws)) = raw_elems(h, v) else {
1506 return Vec::new();
1507 };
1508 raws.iter()
1509 .map(|b| {
1510 if !is_bigint_kind(&kind) {
1511 return h.inspect(&decode(&kind, b));
1512 }
1513 let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1514 if kind == "BigInt64Array" {
1515 format!("{}n", raw as i64)
1516 } else {
1517 format!("{raw}n")
1518 }
1519 })
1520 .collect()
1521}
1522
1523pub fn raw_view_bytes(v: &Value) -> Option<Vec<u8>> {
1528 let kind = super::util_types::ta_kind(v)?;
1529 view_bytes(v, 0, view_len(v) * bytes_per_element(&kind))
1530}
1531
1532fn view_len(v: &Value) -> usize {
1534 if view_detached(v) {
1537 return 0;
1538 }
1539 with_host(|h| match h.get(v) {
1540 Some(JsObj::Object(p)) => p.get("length").map(|l| h.to_number(l)).unwrap_or(0.0) as usize,
1541 _ => 0,
1542 })
1543}
1544
1545pub fn elem_get(recv: &Value, key: &str) -> Option<Value> {
1550 let i: usize = key.parse().ok()?;
1551 if i >= view_len(recv) {
1552 return None;
1553 }
1554 let kind = kind_of(recv);
1555 let bpe = bytes_per_element(&kind);
1556 let bytes = view_bytes(recv, i * bpe, bpe)?;
1557 Some(decode(&kind, &bytes))
1558}
1559
1560pub fn elem_set(recv: &Value, key: &str, val: &Value) -> Result<bool, String> {
1562 let Ok(i) = key.parse::<usize>() else {
1563 return Ok(false);
1564 };
1565 let kind = kind_of(recv);
1566 let n = coerce_val(&kind, val)?;
1569 if i >= view_len(recv) {
1570 return Ok(false);
1571 }
1572 let bpe = bytes_per_element(&kind);
1573 Ok(write_view_bytes(recv, i * bpe, &encode(&kind, &n)))
1574}
1575
1576fn species(recv: &Value, kind: &str, elems: Vec<Value>) -> Value {
1581 if super::native_tag(recv).as_deref() == Some("Buffer") {
1582 let bytes: Vec<u8> = elems.iter().map(|x| num(x) as i64 as u8).collect();
1583 return super::buffer::from_bytes(&bytes);
1584 }
1585 make(kind, elems)
1586}
1587
1588fn write_elems(recv: &Value, kind: &str, vals: &[Value]) -> Result<(), String> {
1593 if super::native_tag(recv).as_deref() == Some("TypedArray") {
1594 let bpe = bytes_per_element(kind);
1595 let coerced: Vec<Value> = vals
1596 .iter()
1597 .map(|v| coerce_val(kind, v))
1598 .collect::<Result<_, _>>()?;
1599 for (i, v) in coerced.iter().enumerate() {
1600 write_view_bytes(recv, i * bpe, &encode(kind, v));
1601 }
1602 return Ok(());
1603 }
1604 let field = "@@bytes";
1605 let coerced: Vec<Value> = vals
1608 .iter()
1609 .map(|v| coerce_val(kind, v))
1610 .collect::<Result<_, _>>()?;
1611 with_host(|h| {
1612 let (arr, off, len) = match h.get(recv) {
1613 Some(JsObj::Object(p)) => {
1614 let (off, len) = super::buffer::window_h(h, p);
1615 (p.get(field).cloned(), off, len)
1616 }
1617 _ => (None, 0, 0),
1618 };
1619 if let Some(JsObj::Array(items)) = arr.as_ref().and_then(|a| h.get_mut(a)) {
1623 for (i, v) in coerced.into_iter().enumerate().take(len) {
1624 items[off + i] = v;
1625 }
1626 }
1627 });
1628 Ok(())
1629}
1630
1631fn sort_elements(elems: &mut Vec<Value>, kind: &str, cmp: Option<&Value>) -> Result<(), String> {
1635 let cmp = cmp.cloned().unwrap_or(Value::Undef);
1636 if with_host(|h| crate::host::is_callable(h, &cmp)) {
1637 return crate::builtins::sort_values(elems, Some(&cmp));
1643 }
1644 if is_bigint_kind(kind) {
1651 let keys: Vec<num_bigint::BigInt> = elems.iter().map(bigint_of).collect();
1652 let mut idx: Vec<usize> = (0..elems.len()).collect();
1653 idx.sort_by(|a, b| keys[*a].cmp(&keys[*b]));
1654 *elems = idx.into_iter().map(|i| elems[i].clone()).collect();
1655 } else {
1656 elems.sort_by(|a, b| match (num(a), num(b)) {
1660 (x, y) if x.is_nan() || y.is_nan() => x.is_nan().cmp(&y.is_nan()),
1661 (x, y) => x.total_cmp(&y),
1662 });
1663 }
1664 Ok(())
1665}
1666
1667fn rel_index(args: &[Value], idx: usize, len: usize, default: usize) -> usize {
1671 if args.len() <= idx {
1672 return default;
1673 }
1674 let n = super::arg_num(args, idx);
1675 if n < 0.0 {
1676 (len as f64 + n).max(0.0) as usize
1677 } else {
1678 (n as usize).min(len)
1679 }
1680}
1681
1682fn base64_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1687 let kind = kind_of(recv);
1688 if kind != "Uint8Array" {
1689 return Err(crate::host::type_error(&format!(
1696 "Method Uint8Array.prototype.{method} called on incompatible receiver undefined"
1697 )));
1698 }
1699 let bytes: Vec<u8> = elem_values(recv)
1700 .iter()
1701 .map(|v| with_host(|h| h.to_number(v)) as u8)
1702 .collect();
1703 match method {
1704 "toBase64" => {
1705 let (url, _) = base64_options(args.first())?;
1706 let omit = args
1707 .first()
1708 .filter(|v| !matches!(v, Value::Undef))
1709 .map(|o| {
1710 with_host(|h| match h.get(o) {
1711 Some(JsObj::Object(p)) => {
1712 p.get("omitPadding").map(|v| h.truthy(v)).unwrap_or(false)
1713 }
1714 _ => false,
1715 })
1716 })
1717 .unwrap_or(false);
1718 let mut s = super::to_base64(&bytes);
1721 if url {
1722 s = s.replace('+', "-").replace('/', "_");
1723 }
1724 if omit {
1725 s = s.trim_end_matches('=').to_string();
1726 }
1727 Ok(with_host(|h| h.new_str(s)))
1728 }
1729 "toHex" => Ok(with_host(|h| h.new_str(super::to_hex(&bytes)))),
1730 "setFromBase64" | "setFromHex" => {
1733 let s = base64_input(args)?;
1734 let (decoded, read) = if method == "setFromHex" {
1735 let d = decode_hex_strict(&s)?;
1736 let fits = d.len().min(bytes.len());
1737 (d[..fits].to_vec(), fits * 2)
1738 } else {
1739 let (url, last) = base64_options(args.get(1))?;
1740 let whole = (bytes.len() / 3) * 4;
1743 let head: String = s.chars().take(whole).collect();
1744 let (mut d, mut consumed) = decode_base64_strict(&head, url, last)?;
1745 if d.len() < bytes.len() {
1746 let (full, full_read) = decode_base64_strict(&s, url, last)?;
1747 if full.len() <= bytes.len() {
1748 d = full;
1749 consumed = full_read;
1750 }
1751 }
1752 (d, consumed)
1753 };
1754 write_view_bytes(recv, 0, &decoded);
1755 Ok(with_host(|h| {
1756 let mut m = IndexMap::new();
1757 m.insert("read".to_string(), Value::Float(read as f64));
1758 m.insert("written".to_string(), Value::Float(decoded.len() as f64));
1759 h.new_object(m)
1760 }))
1761 }
1762 _ => unreachable!("caller gates the method name"),
1763 }
1764}
1765
1766pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1767 if view_detached(recv) {
1771 return Err(detached_error("%TypedArray%.prototype", method, false));
1772 }
1773 if matches!(
1774 method,
1775 "toBase64" | "toHex" | "setFromBase64" | "setFromHex"
1776 ) {
1777 return base64_instance_call(recv, method, args);
1778 }
1779 let kind = kind_of(recv);
1780 let elems = elem_values(recv);
1785 let this_arg = args.get(1).filter(|v| !matches!(v, Value::Undef)).cloned();
1791 let call_cb = |i: usize, v: &Value| -> Result<Value, String> {
1792 crate::host::invoke(
1793 &args.first().cloned().unwrap_or(Value::Undef),
1794 vec![v.clone(), Value::Float(i as f64), recv.clone()],
1795 this_arg.clone(),
1796 )
1797 };
1798 match method {
1799 "every" => {
1800 for (i, v) in elems.iter().enumerate() {
1801 let r = call_cb(i, v)?;
1802 if !with_host(|h| h.truthy(&r)) {
1803 return Ok(Value::Bool(false));
1804 }
1805 }
1806 Ok(Value::Bool(true))
1807 }
1808 "some" => {
1809 for (i, v) in elems.iter().enumerate() {
1810 let r = call_cb(i, v)?;
1811 if with_host(|h| h.truthy(&r)) {
1812 return Ok(Value::Bool(true));
1813 }
1814 }
1815 Ok(Value::Bool(false))
1816 }
1817 "forEach" => {
1818 for (i, v) in elems.iter().enumerate() {
1819 call_cb(i, v)?;
1820 }
1821 Ok(Value::Undef)
1822 }
1823 "map" => {
1824 let mut out = Vec::with_capacity(elems.len());
1825 for (i, v) in elems.iter().enumerate() {
1826 let r = call_cb(i, v)?;
1827 out.push(coerce_val(&kind, &r)?);
1828 }
1829 Ok(species(recv, &kind, out))
1830 }
1831 "filter" => {
1832 let mut out = Vec::new();
1833 for (i, v) in elems.iter().enumerate() {
1834 let r = call_cb(i, v)?;
1835 if with_host(|h| h.truthy(&r)) {
1836 out.push(v.clone());
1837 }
1838 }
1839 Ok(species(recv, &kind, out))
1840 }
1841 "find" | "findIndex" | "findLast" | "findLastIndex" => {
1842 let last = method.starts_with("findLast");
1843 let idxs: Vec<usize> = if last {
1844 (0..elems.len()).rev().collect()
1845 } else {
1846 (0..elems.len()).collect()
1847 };
1848 for i in idxs {
1849 let r = call_cb(i, &elems[i])?;
1850 if with_host(|h| h.truthy(&r)) {
1851 return Ok(if method.ends_with("Index") {
1852 Value::Float(i as f64)
1853 } else {
1854 elems[i].clone()
1855 });
1856 }
1857 }
1858 Ok(if method.ends_with("Index") {
1859 Value::Float(-1.0)
1860 } else {
1861 Value::Undef
1862 })
1863 }
1864 "reduce" | "reduceRight" => {
1865 let right = method == "reduceRight";
1866 let order: Vec<usize> = if right {
1867 (0..elems.len()).rev().collect()
1868 } else {
1869 (0..elems.len()).collect()
1870 };
1871 let cb = args.first().cloned().unwrap_or(Value::Undef);
1872 let mut it = order.into_iter();
1873 let mut acc = if args.len() >= 2 {
1874 args[1].clone()
1875 } else {
1876 match it.next() {
1877 Some(i) => elems[i].clone(),
1878 None => {
1879 return Err(crate::host::type_error(
1880 "Reduce of empty array with no initial value",
1881 ))
1882 }
1883 }
1884 };
1885 for i in it {
1886 acc = crate::host::invoke(
1887 &cb,
1888 vec![acc, elems[i].clone(), Value::Float(i as f64), recv.clone()],
1889 None,
1890 )?;
1891 }
1892 Ok(acc)
1893 }
1894 "reverse" => {
1895 let mut out = elems.clone();
1896 out.reverse();
1897 write_elems(recv, &kind, &out)?;
1898 Ok(recv.clone())
1899 }
1900 "sort" => {
1901 let mut out = elems.clone();
1902 sort_elements(&mut out, &kind, args.first())?;
1903 write_elems(recv, &kind, &out)?;
1904 Ok(recv.clone())
1905 }
1906 "copyWithin" => {
1907 let len = elems.len();
1908 let target = rel_index(args, 0, len, 0);
1909 let start = rel_index(args, 1, len, 0);
1910 let end = rel_index(args, 2, len, len);
1911 let src: Vec<Value> = elems[start.min(end)..end.max(start)].to_vec();
1912 let mut out = elems.clone();
1913 for (k, v) in src.iter().enumerate() {
1914 if target + k < len {
1915 out[target + k] = v.clone();
1916 }
1917 }
1918 write_elems(recv, &kind, &out)?;
1919 Ok(recv.clone())
1920 }
1921 "at" => {
1922 let n = super::arg_num(args, 0);
1923 let i = if n < 0.0 { elems.len() as f64 + n } else { n };
1924 if i < 0.0 || i >= elems.len() as f64 {
1925 return Ok(Value::Undef);
1926 }
1927 Ok(elems[i as usize].clone())
1928 }
1929 "lastIndexOf" => {
1930 let needle = args.first().cloned().unwrap_or(Value::Undef);
1931 let from = (args.len() > 1).then(|| super::arg_num(args, 1));
1932 let found = crate::builtins::search_start_last(from, elems.len()).and_then(|start| {
1933 elems[..=start]
1934 .iter()
1935 .rposition(|x| same_element(x, &needle, false))
1936 });
1937 Ok(Value::Float(found.map(|p| p as f64).unwrap_or(-1.0)))
1938 }
1939 "keys" | "values" | "entries" | "@@iterator" => {
1944 let items: Vec<Value> = with_host(|h| match method {
1945 "keys" => (0..elems.len()).map(|i| Value::Float(i as f64)).collect(),
1946 "values" | "@@iterator" => elems.clone(),
1947 _ => elems
1948 .iter()
1949 .enumerate()
1950 .map(|(i, v)| h.new_array(vec![Value::Float(i as f64), v.clone()]))
1951 .collect(),
1952 });
1953 Ok(with_host(|h| {
1954 h.alloc_iter(JsObj::Iter {
1955 items,
1956 idx: 0,
1957 array: None,
1958 brand: Some("Array Iterator"),
1959 })
1960 }))
1961 }
1962 "toString" | "join" => {
1963 let sep = if method == "join" && !args.is_empty() {
1964 super::arg_str(args, 0)
1965 } else {
1966 ",".into()
1967 };
1968 let parts: Vec<String> = with_host(|h| elems.iter().map(|n| h.str_of(n)).collect());
1969 Ok(with_host(|h| h.new_str(parts.join(&sep))))
1970 }
1971 "slice" | "subarray" => {
1972 let len = elems.len();
1973 let norm = |n: f64| -> usize {
1974 if n < 0.0 {
1975 (len as f64 + n).max(0.0) as usize
1976 } else {
1977 (n as usize).min(len)
1978 }
1979 };
1980 let s = if args.is_empty() {
1981 0
1982 } else {
1983 norm(super::arg_num(args, 0))
1984 };
1985 let e = if args.len() < 2 {
1986 len
1987 } else {
1988 norm(super::arg_num(args, 1))
1989 };
1990 let (lo, hi) = (s.min(e), e.max(s));
1991 if method == "subarray" && super::native_tag(recv).as_deref() == Some("TypedArray") {
1994 if let Some((buf, off)) = view_base(recv) {
1995 let bpe = bytes_per_element(&kind);
1996 return Ok(make_view(&kind, &buf, off + lo * bpe, hi - lo));
1997 }
1998 }
1999 Ok(species(recv, &kind, elems[lo..hi].to_vec()))
2000 }
2001 "indexOf" => {
2002 let needle = args.first().cloned().unwrap_or(Value::Undef);
2003 let start = crate::builtins::search_start(super::arg_num(args, 1), elems.len());
2004 Ok(Value::Float(
2005 elems
2006 .iter()
2007 .skip(start)
2008 .position(|x| same_element(x, &needle, false))
2009 .map(|p| (p + start) as f64)
2010 .unwrap_or(-1.0),
2011 ))
2012 }
2013 "includes" => {
2014 let needle = args.first().cloned().unwrap_or(Value::Undef);
2015 let start = crate::builtins::search_start(super::arg_num(args, 1), elems.len());
2016 Ok(Value::Bool(
2017 elems
2018 .iter()
2019 .skip(start)
2020 .any(|x| same_element(x, &needle, true)),
2021 ))
2022 }
2023 "fill" => {
2030 let len = elems.len();
2031 let v = coerce_val(&kind, args.first().unwrap_or(&Value::Undef))?;
2032 let start = rel_index(args, 1, len, 0);
2033 let end = rel_index(args, 2, len, len);
2034 let mut out = elems.clone();
2035 for slot in out.iter_mut().take(end).skip(start) {
2036 *slot = v.clone();
2037 }
2038 write_elems(recv, &kind, &out)?;
2039 Ok(recv.clone())
2040 }
2041 "toReversed" | "toSorted" => {
2046 let mut out = elems.clone();
2047 if method == "toReversed" {
2048 out.reverse();
2049 } else {
2050 sort_elements(&mut out, &kind, args.first())?;
2051 }
2052 Ok(make(&kind, out))
2053 }
2054 "with" => {
2055 let len = elems.len();
2056 let n = super::arg_num(args, 0);
2057 let i = if n < 0.0 { len as f64 + n } else { n };
2058 if !(0.0..len as f64).contains(&i) {
2059 return Err("RangeError: Invalid typed array index".into());
2060 }
2061 let mut out = elems.clone();
2062 out[i as usize] = coerce_val(&kind, args.get(1).unwrap_or(&Value::Undef))?;
2063 Ok(make(&kind, out))
2064 }
2065 "set" => {
2066 let src = set_source(args.first());
2068 let off = super::arg_num(args, 1);
2071 let off = if off.is_nan() { 0.0 } else { off.trunc() };
2072 if off < 0.0 || off + src.len() as f64 > view_len(recv) as f64 {
2073 return Err(crate::host::range_error("offset is out of bounds"));
2074 }
2075 let off = off as usize;
2076 let src: Vec<Value> = src
2078 .iter()
2079 .map(|v| coerce_val(&kind, v))
2080 .collect::<Result<_, _>>()?;
2081 let bpe = bytes_per_element(&kind);
2082 let len = view_len(recv);
2083 for (k, v) in src.into_iter().enumerate() {
2084 if off + k < len {
2085 write_view_bytes(recv, (off + k) * bpe, &encode(&kind, &v));
2086 }
2087 }
2088 Ok(Value::Undef)
2089 }
2090 _ => Err(crate::host::type_error(&format!(
2091 "{method} is not a function"
2092 ))),
2093 }
2094}
2095
2096pub fn set_source(arg: Option<&Value>) -> Vec<Value> {
2100 let arg = arg.cloned().unwrap_or(Value::Undef);
2101 match super::native_tag(&arg).as_deref() {
2102 Some("TypedArray") | Some("Buffer") => elem_values(&arg),
2103 _ => {
2104 crate::host::iter_all(&arg).unwrap_or_else(|_| crate::builtins::array_like_items(&arg))
2105 }
2106 }
2107}
2108
2109pub fn set_source_bytes(arg: Option<&Value>) -> Result<Vec<u8>, String> {
2111 set_source(arg)
2112 .iter()
2113 .map(|v| coerce_val("Uint8Array", v).map(|e| with_host(|h| h.to_number(&e)) as u8))
2114 .collect()
2115}
2116
2117pub fn construct_weakref(args: &[Value]) -> Result<Value, String> {
2120 let target = args.first().cloned().unwrap_or(Value::Undef);
2121 Ok(with_host(|h| {
2122 let mut m = IndexMap::new();
2123 m.insert("@@native".into(), h.new_str("WeakRef"));
2124 m.insert("@@target".into(), target);
2125 h.new_object(m)
2126 }))
2127}
2128
2129pub fn weakref_call(recv: &Value, method: &str) -> Result<Value, String> {
2130 match method {
2131 "deref" => Ok(with_host(|h| match h.get(recv) {
2132 Some(JsObj::Object(p)) => p.get("@@target").cloned().unwrap_or(Value::Undef),
2133 _ => Value::Undef,
2134 })),
2135 _ => Err(crate::host::type_error(&format!(
2136 "{method} is not a function"
2137 ))),
2138 }
2139}
2140
2141fn is_object_value(v: &Value) -> bool {
2154 matches!(v, Value::Obj(_))
2155 && with_host(|h| {
2156 !matches!(
2157 h.get(v),
2158 Some(JsObj::Str(_))
2159 | Some(JsObj::Symbol { .. })
2160 | Some(JsObj::BigInt(_))
2161 | Some(JsObj::Null)
2162 )
2163 })
2164}
2165
2166pub fn construct_finalization_registry(args: &[Value]) -> Result<Value, String> {
2167 let cb = args.first().cloned().unwrap_or(Value::Undef);
2168 if !with_host(|h| crate::host::is_callable(h, &cb)) {
2169 return Err(crate::host::type_error(
2170 "FinalizationRegistry: cleanup must be callable",
2171 ));
2172 }
2173 Ok(with_host(|h| {
2174 let tokens = h.new_array(Vec::new());
2175 let mut m = IndexMap::new();
2176 m.insert("@@native".into(), h.new_str("FinalizationRegistry"));
2177 m.insert("@@fr_cb".into(), cb);
2178 m.insert("@@fr_tokens".into(), tokens);
2179 h.new_object(m)
2180 }))
2181}
2182
2183pub fn finalization_registry_call(
2184 recv: &Value,
2185 method: &str,
2186 args: &[Value],
2187) -> Result<Value, String> {
2188 match method {
2189 "register" => {
2190 let target = args.first().cloned().unwrap_or(Value::Undef);
2191 let held = args.get(1).cloned().unwrap_or(Value::Undef);
2192 let token = args.get(2).cloned().unwrap_or(Value::Undef);
2193 if !is_object_value(&target) {
2194 return Err(crate::host::type_error(
2197 "FinalizationRegistry.prototype.register: invalid target",
2198 ));
2199 }
2200 if with_host(|h| h.strict_eq(&target, &held)) {
2201 return Err(crate::host::type_error(
2202 "FinalizationRegistry.prototype.register: target and holdings must not be same",
2203 ));
2204 }
2205 if !matches!(token, Value::Undef) {
2208 if !is_object_value(&token) {
2209 return Err(crate::host::type_error(&format!(
2210 "Invalid unregisterToken ('{}')",
2211 with_host(|h| h.str_of(&token))
2212 )));
2213 }
2214 with_host(|h| {
2215 let toks = registry_tokens(h, recv);
2216 if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
2217 items.push(token);
2218 }
2219 });
2220 }
2221 Ok(Value::Undef)
2222 }
2223 "unregister" => {
2224 let token = args.first().cloned().unwrap_or(Value::Undef);
2225 if !is_object_value(&token) {
2226 return Err(crate::host::type_error(&format!(
2228 "Invalid unregisterToken ('{}')",
2229 with_host(|h| h.str_of(&token))
2230 )));
2231 }
2232 Ok(Value::Bool(with_host(|h| {
2233 let toks = registry_tokens(h, recv);
2234 let kept: Vec<Value> = match h.get(&toks) {
2235 Some(JsObj::Array(items)) => items
2236 .iter()
2237 .filter(|t| !h.strict_eq(t, &token))
2238 .cloned()
2239 .collect(),
2240 _ => Vec::new(),
2241 };
2242 let removed = match h.get(&toks) {
2243 Some(JsObj::Array(items)) => items.len() != kept.len(),
2244 _ => false,
2245 };
2246 if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
2247 *items = kept;
2248 }
2249 removed
2250 })))
2251 }
2252 _ => Err(crate::host::type_error(&format!(
2253 "{method} is not a function"
2254 ))),
2255 }
2256}
2257
2258fn registry_tokens(h: &crate::host::JsHost, recv: &Value) -> Value {
2260 match h.get(recv) {
2261 Some(JsObj::Object(p)) => p.get("@@fr_tokens").cloned().unwrap_or(Value::Undef),
2262 _ => Value::Undef,
2263 }
2264}
2265
2266pub fn construct_text_encoder() -> Result<Value, String> {
2269 Ok(with_host(|h| {
2270 let mut m = IndexMap::new();
2271 m.insert("@@native".into(), h.new_str("TextEncoder"));
2272 m.insert("@@encoding".into(), h.new_str("utf-8"));
2277 h.new_object(m)
2278 }))
2279}
2280
2281pub fn text_encoder_call(_recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2282 match method {
2283 "encode" => {
2288 let s = match args.first() {
2289 None | Some(Value::Undef) => String::new(),
2290 Some(v) => {
2291 let s = crate::host::to_string_value(v)?;
2292 with_host(|h| h.str_of(&s))
2293 }
2294 };
2295 Ok(make(
2296 "Uint8Array",
2297 s.as_bytes()
2298 .iter()
2299 .map(|b| Value::Float(*b as f64))
2300 .collect(),
2301 ))
2302 }
2303 "encodeInto" => {
2307 let src = args.first().cloned().unwrap_or(Value::Undef);
2308 let Some(s) = with_host(|h| h.as_str(&src)) else {
2309 return Err(crate::host::invalid_arg_type(
2310 "src", "argument", "string", &src,
2311 ));
2312 };
2313 let dest = args.get(1).cloned().unwrap_or(Value::Undef);
2314 if super::util_types::ta_kind(&dest).as_deref() != Some("Uint8Array") {
2315 return Err(crate::host::coded_error(
2316 "TypeError",
2317 "ERR_INVALID_ARG_TYPE",
2318 &format!(
2319 "The \"dest\" argument must be an instance of Uint8Array. Received {}",
2320 super::received_desc(&dest)
2321 ),
2322 ));
2323 }
2324 let mut out = super::buffer::view_bytes(&dest).unwrap_or_default();
2325 let (mut read, mut written) = (0, 0);
2326 for c in s.chars() {
2327 let n = c.len_utf8();
2328 if written + n > out.len() {
2329 break;
2330 }
2331 c.encode_utf8(&mut out[written..written + n]);
2332 written += n;
2333 read += c.len_utf16();
2334 }
2335 super::buffer::write_view(&dest, &out);
2336 Ok(with_host(|h| {
2337 let mut m = IndexMap::new();
2338 m.insert("read".into(), Value::Float(read as f64));
2339 m.insert("written".into(), Value::Float(written as f64));
2340 h.new_object(m)
2341 }))
2342 }
2343 _ => Err(crate::host::type_error(&format!(
2344 "{method} is not a function"
2345 ))),
2346 }
2347}
2348
2349fn encoding_for_label(label: &str) -> Option<&'static str> {
2356 Some(match label.trim().to_ascii_lowercase().as_str() {
2357 "utf-8" | "utf8" | "unicode-1-1-utf-8" | "unicode11utf8" | "unicode20utf8"
2358 | "x-unicode20utf8" => "utf-8",
2359 "latin1" | "iso-8859-1" | "iso8859-1" | "iso88591" | "ascii" | "us-ascii" | "cp1252"
2360 | "cp819" | "ibm819" | "l1" | "windows-1252" | "x-cp1252" => "windows-1252",
2361 "utf-16le" | "utf-16" | "ucs-2" | "ucs2" | "unicodefeff" | "unicodefffe"
2362 | "iso-10646-ucs-2" | "csunicode" => "utf-16le",
2363 _ => return None,
2364 })
2365}
2366
2367pub fn construct_text_decoder(args: &[Value]) -> Result<Value, String> {
2368 let label = if args.is_empty() || matches!(args[0], Value::Undef) {
2369 "utf-8".to_string()
2370 } else {
2371 super::arg_str(args, 0)
2372 };
2373 let Some(encoding) = encoding_for_label(&label) else {
2374 return Err(crate::host::coded_error(
2375 "RangeError",
2376 "ERR_ENCODING_NOT_SUPPORTED",
2377 &format!("The \"{label}\" encoding is not supported"),
2378 ));
2379 };
2380 let flag = |key: &str| {
2384 args.get(1)
2385 .map(|o| crate::builtins::get_property(o, key).unwrap_or(Value::Undef))
2386 .map(|v| with_host(|h| h.truthy(&v)))
2387 .unwrap_or(false)
2388 };
2389 let (fatal, ignore_bom) = (flag("fatal"), flag("ignoreBOM"));
2390 Ok(with_host(|h| {
2391 let mut m = IndexMap::new();
2392 m.insert("@@native".into(), h.new_str("TextDecoder"));
2393 m.insert("@@encoding".into(), h.new_str(encoding.to_string()));
2394 m.insert("@@fatal".into(), Value::Bool(fatal));
2395 m.insert("@@ignoreBOM".into(), Value::Bool(ignore_bom));
2396 h.new_object(m)
2397 }))
2398}
2399
2400const CP1252_HIGH: [char; 32] = [
2406 '\u{20ac}', '\u{81}', '\u{201a}', '\u{192}', '\u{201e}', '\u{2026}', '\u{2020}', '\u{2021}',
2407 '\u{2c6}', '\u{2030}', '\u{160}', '\u{2039}', '\u{152}', '\u{8d}', '\u{17d}', '\u{8f}',
2408 '\u{90}', '\u{2018}', '\u{2019}', '\u{201c}', '\u{201d}', '\u{2022}', '\u{2013}', '\u{2014}',
2409 '\u{2dc}', '\u{2122}', '\u{161}', '\u{203a}', '\u{153}', '\u{9d}', '\u{17e}', '\u{178}',
2410];
2411
2412fn incomplete_tail(bytes: &[u8], enc: &str) -> usize {
2418 match enc {
2419 "utf-16le" => bytes.len() % 2,
2420 "utf-8" => match std::str::from_utf8(bytes) {
2421 Err(e) if e.error_len().is_none() => bytes.len() - e.valid_up_to(),
2422 _ => 0,
2423 },
2424 _ => 0,
2425 }
2426}
2427pub fn text_decoder_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2428 match method {
2429 "decode" => {
2431 let input = args.first().cloned().unwrap_or(Value::Undef);
2436 let fresh = match &input {
2437 Value::Undef => Vec::new(),
2438 v => super::buffer::view_bytes(v).ok_or_else(|| {
2439 crate::host::coded_error(
2440 "TypeError",
2441 "ERR_INVALID_ARG_TYPE",
2442 "The \"list\" argument must be an instance of SharedArrayBuffer, \
2443 ArrayBuffer or ArrayBufferView.",
2444 )
2445 })?,
2446 };
2447 let stream = args
2448 .get(1)
2449 .map(|o| crate::builtins::get_property(o, "stream").unwrap_or(Value::Undef))
2450 .is_some_and(|v| with_host(|h| h.truthy(&v)));
2451 let slot = |key: &str| {
2452 with_host(|h| match h.get(recv) {
2453 Some(JsObj::Object(p)) => p.get(key).cloned(),
2454 _ => None,
2455 })
2456 };
2457 let enc = slot("@@encoding")
2458 .map(|v| with_host(|h| h.str_of(&v)))
2459 .unwrap_or_else(|| "utf-8".into());
2460 let flag = |key: &str| matches!(slot(key), Some(Value::Bool(true)));
2461 let mut bytes: Vec<u8> = slot("@@pending")
2466 .map(|v| {
2467 with_host(|h| h.str_of(&v))
2468 .chars()
2469 .map(|c| c as u8)
2470 .collect()
2471 })
2472 .unwrap_or_default();
2473 bytes.extend(fresh);
2474 let keep = if stream {
2475 incomplete_tail(&bytes, &enc)
2476 } else {
2477 0
2478 };
2479 let held: String = bytes
2480 .split_off(bytes.len() - keep)
2481 .iter()
2482 .map(|b| *b as char)
2483 .collect();
2484 let continuing = flag("@@streaming");
2487 with_host(|h| {
2488 let held = h.new_str(held);
2489 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2490 p.insert("@@pending".into(), held);
2491 p.insert("@@streaming".into(), Value::Bool(stream));
2492 }
2493 });
2494 let s = match enc.as_str() {
2495 "windows-1252" => bytes
2496 .iter()
2497 .map(|b| match b {
2498 0x80..=0x9f => CP1252_HIGH[(b - 0x80) as usize],
2499 _ => *b as char,
2500 })
2501 .collect(),
2502 "utf-16le" => {
2503 let units: Vec<u16> = bytes
2504 .chunks_exact(2)
2505 .map(|c| u16::from_le_bytes([c[0], c[1]]))
2506 .collect();
2507 String::from_utf16_lossy(&units)
2508 }
2509 _ if flag("@@fatal") => match std::str::from_utf8(&bytes) {
2514 Ok(s) => s.to_string(),
2515 Err(_) => {
2516 return Err(crate::host::coded_error(
2517 "TypeError",
2518 "ERR_ENCODING_INVALID_ENCODED_DATA",
2519 &format!("The encoded data was not valid for encoding {enc}"),
2520 ))
2521 }
2522 },
2523 _ => String::from_utf8_lossy(&bytes).into_owned(),
2524 };
2525 let s = match s.strip_prefix('\u{feff}') {
2527 Some(rest) if !continuing && !flag("@@ignoreBOM") => rest.to_string(),
2528 _ => s,
2529 };
2530 Ok(with_host(|h| h.new_str(s)))
2531 }
2532 _ => Err(crate::host::type_error(&format!(
2533 "{method} is not a function"
2534 ))),
2535 }
2536}