1use super::{arg_str, from_base64, from_hex, to_base64, to_hex};
8use crate::host::{with_host, JsObj};
9use fusevm::Value;
10use indexmap::IndexMap;
11
12pub const STATIC_METHODS: &[&str] = &[
30 "from",
31 "copyBytesFrom",
32 "alloc",
33 "allocUnsafe",
34 "allocUnsafeSlow",
35 "concat",
36 "isBuffer",
37 "isEncoding",
38 "byteLength",
39 "compare",
40 "of",
41];
42
43pub const INSTANCE_METHODS: &[&str] = &[
47 "toString",
48 "set",
49 "toJSON",
50 "equals",
51 "slice",
52 "subarray",
53 "readUInt8",
54 "includes",
55 "indexOf",
56 "lastIndexOf",
57 "write",
58 "copy",
59 "fill",
60 "compare",
61 "readUInt16BE",
62 "readUInt16LE",
63 "writeUInt8",
64 "writeInt8",
65 "writeInt16BE",
66 "writeInt16LE",
67 "readFloatBE",
68 "readFloatLE",
69 "writeFloatBE",
70 "writeFloatLE",
71 "readDoubleBE",
72 "readDoubleLE",
73 "writeDoubleBE",
74 "writeDoubleLE",
75 "readBigInt64BE",
76 "readBigInt64LE",
77 "readBigUInt64BE",
78 "readBigUInt64LE",
79 "writeBigInt64BE",
80 "writeBigInt64LE",
81 "writeBigUInt64BE",
82 "writeBigUInt64LE",
83 "readIntBE",
84 "readIntLE",
85 "readUIntBE",
86 "readUIntLE",
87 "writeIntBE",
88 "writeIntLE",
89 "writeUIntBE",
90 "writeUIntLE",
91 "writeUInt16BE",
92 "writeUInt16LE",
93 "readUInt32BE",
94 "readUInt32LE",
95 "readInt8",
96 "readInt16BE",
97 "readInt16LE",
98 "readInt32BE",
99 "readInt32LE",
100 "writeUInt32BE",
101 "writeUInt32LE",
102 "writeInt32BE",
103 "writeInt32LE",
104 "at",
105 "values",
106 "keys",
107 "entries",
108 "swap16",
109 "swap32",
110 "swap64",
111];
112
113pub const MODULE_METHODS: &[&str] = &["atob", "btoa", "isAscii", "isLatin1", "isUtf8", "transcode"];
117
118pub fn module_constant(name: &str) -> Option<Value> {
122 const MAX_STRING_LENGTH: f64 = 536_870_888.0;
123 match name {
124 "kMaxLength" => Some(Value::Float(K_MAX_LENGTH)),
125 "kStringMaxLength" => Some(Value::Float(MAX_STRING_LENGTH)),
126 "INSPECT_MAX_BYTES" => Some(Value::Float(50.0)),
127 "constants" => Some(with_host(|h| {
128 let mut m = IndexMap::new();
129 m.insert("MAX_LENGTH".into(), Value::Float(K_MAX_LENGTH));
130 m.insert("MAX_STRING_LENGTH".into(), Value::Float(MAX_STRING_LENGTH));
131 h.new_object(m)
132 })),
133 _ => None,
134 }
135}
136
137fn string_input(args: &[Value]) -> Result<String, String> {
141 let v = args.first().ok_or_else(|| {
142 crate::host::coded_error(
143 "TypeError",
144 "ERR_MISSING_ARGS",
145 "The \"input\" argument must be specified",
146 )
147 })?;
148 let s = crate::host::to_string_value(v)?;
149 Ok(with_host(|h| h.str_of(&s)))
150}
151
152fn validated_bytes(args: &[Value]) -> Result<Vec<u8>, String> {
157 let v = args.first().cloned().unwrap_or(Value::Undef);
158 match super::native_tag(&v).as_deref() {
159 Some("Buffer" | "TypedArray" | "ArrayBuffer") => Ok(view_bytes(&v).unwrap_or_default()),
160 _ => Err(crate::host::coded_error(
161 "TypeError",
162 "ERR_INVALID_ARG_TYPE",
163 &format!(
164 "The \"input\" argument must be an instance of ArrayBuffer, Buffer, or TypedArray. Received {}",
165 super::received_desc(&v)
166 ),
167 )),
168 }
169}
170
171fn forgiving_base64(s: &str) -> Result<Vec<u8>, String> {
177 let invalid = || crate::host::dom_error("InvalidCharacterError", "Invalid character");
178 let chars: Vec<char> = s
179 .chars()
180 .filter(|c| !matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' '))
181 .collect();
182 let pad = chars.iter().rev().take_while(|c| **c == '=').count();
183 let data = &chars[..chars.len() - pad];
184 let mut vals = Vec::with_capacity(data.len());
185 for c in data {
186 match B64_ALPHABET.find(*c) {
187 Some(i) => vals.push(i as u32),
188 None => return Err(invalid()),
189 }
190 }
191 if pad > 2 {
192 return Err(invalid());
193 }
194 if vals.len() % 4 == 1 {
195 return Err(crate::host::dom_error(
196 "InvalidCharacterError",
197 "The string to be decoded is not correctly encoded.",
198 ));
199 }
200 if pad > 0 && chars.len() % 4 != 0 {
201 return Err(invalid());
202 }
203 let mut out = Vec::with_capacity(vals.len() * 3 / 4);
204 for q in vals.chunks(4) {
205 let n = q
206 .iter()
207 .enumerate()
208 .fold(0u32, |n, (i, v)| n | v << (18 - 6 * i));
209 out.extend_from_slice(&n.to_be_bytes()[1..q.len()]);
210 }
211 Ok(out)
212}
213
214const B64_ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
215
216pub fn module_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
218 Some(match method {
219 "atob" => (|| {
221 let bytes = forgiving_base64(&string_input(args)?)?;
222 let bin: String = bytes.iter().map(|b| *b as char).collect();
223 Ok(with_host(|h| h.new_str(bin)))
224 })(),
225 "btoa" => (|| {
229 let s = string_input(args)?;
230 let bytes = s
231 .chars()
232 .map(|c| u8::try_from(c as u32))
233 .collect::<Result<Vec<u8>, _>>()
234 .map_err(|_| {
235 crate::host::dom_error("InvalidCharacterError", "Invalid character")
236 })?;
237 Ok(with_host(|h| h.new_str(to_base64(&bytes))))
238 })(),
239 "isAscii" => validated_bytes(args).map(|b| Value::Bool(b.is_ascii())),
240 "isUtf8" => validated_bytes(args).map(|b| Value::Bool(std::str::from_utf8(&b).is_ok())),
241 "isLatin1" => {
244 let v = args.first().cloned().unwrap_or(Value::Undef);
245 match with_host(|h| h.as_str(&v)) {
246 Some(s) => Ok(Value::Bool(s.chars().all(|c| (c as u32) < 0x100))),
247 None => Err(crate::host::invalid_arg_type(
248 "input", "argument", "string", &v,
249 )),
250 }
251 }
252 "transcode" => {
255 let src = input_bytes(args.first());
256 let from = arg_str(args, 1);
257 let to = arg_str(args, 2);
258 let s = bytes_to_string(&src, &from);
259 let out = string_to_bytes(&s, &to);
260 Ok(from_bytes(&out))
261 }
262 _ => return None,
263 })
264}
265
266fn input_bytes(v: Option<&Value>) -> Vec<u8> {
268 match v {
269 None => Vec::new(),
270 Some(v) => {
271 if let Some(s) = with_host(|h| h.as_str(v)) {
272 s.into_bytes()
273 } else {
274 bytes_of(v)
275 }
276 }
277 }
278}
279
280fn bytes_to_string(bytes: &[u8], enc: &str) -> String {
282 match enc.to_ascii_lowercase().as_str() {
283 "ascii" | "latin1" | "binary" => bytes.iter().map(|b| *b as char).collect(),
284 "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
285 let units: Vec<u16> = bytes
286 .chunks_exact(2)
287 .map(|c| u16::from_le_bytes([c[0], c[1]]))
288 .collect();
289 String::from_utf16_lossy(&units)
290 }
291 _ => String::from_utf8_lossy(bytes).into_owned(),
292 }
293}
294
295fn string_to_bytes(s: &str, enc: &str) -> Vec<u8> {
301 match enc.to_ascii_lowercase().as_str() {
302 "ascii" => s
303 .chars()
304 .map(|c| if c.is_ascii() { c as u8 } else { b'?' })
305 .collect(),
306 "latin1" | "binary" => s.chars().map(|c| c as u32 as u8).collect(),
307 "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
308 s.encode_utf16().flat_map(|u| u.to_le_bytes()).collect()
309 }
310 _ => s.as_bytes().to_vec(),
311 }
312}
313
314fn part_bytes(v: &Value) -> Vec<u8> {
324 match with_host(|h| h.as_str(v)) {
325 Some(s) => s.into_bytes(),
326 None => bytes_of(v),
327 }
328}
329
330fn gather_parts(parts: &Value) -> Vec<u8> {
332 let items = with_host(|h| match h.get(parts) {
333 Some(JsObj::Array(it)) => it.clone(),
334 _ => Vec::new(),
335 });
336 let mut out = Vec::new();
337 for it in &items {
338 out.extend(part_bytes(it));
339 }
340 out
341}
342
343fn opt_type(opts: Option<&Value>) -> String {
345 match opts {
346 Some(v) => with_host(|h| match h.get(v) {
347 Some(JsObj::Object(p)) => p.get("type").map(|x| h.str_of(x)).unwrap_or_default(),
348 _ => String::new(),
349 }),
350 None => String::new(),
351 }
352}
353
354fn build_blob(tag: &str, bytes: &[u8], typ: &str, extra: IndexMap<String, Value>) -> Value {
357 with_host(|h| {
358 let arr = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
359 let mut m = IndexMap::new();
360 m.insert("@@native".into(), h.new_str(tag.to_string()));
361 m.insert("@@bytes".into(), arr);
362 m.insert("size".into(), Value::Float(bytes.len() as f64));
363 m.insert("type".into(), h.new_str(typ.to_string()));
364 for (k, v) in extra {
365 m.insert(k, v);
366 }
367 h.new_object(m)
368 })
369}
370
371pub fn construct_blob(args: &[Value]) -> Result<Value, String> {
373 let bytes = gather_parts(&args.first().cloned().unwrap_or(Value::Undef));
374 let typ = opt_type(args.get(1));
375 Ok(build_blob("Blob", &bytes, &typ, IndexMap::new()))
376}
377
378pub fn construct_file(args: &[Value]) -> Result<Value, String> {
380 let bytes = gather_parts(&args.first().cloned().unwrap_or(Value::Undef));
381 let name = arg_str(args, 1);
382 let typ = opt_type(args.get(2));
383 let last_modified = args
385 .get(2)
386 .map(|v| {
387 with_host(|h| match h.get(v) {
388 Some(JsObj::Object(p)) => {
389 p.get("lastModified").map(|x| h.to_number(x)).unwrap_or(0.0)
390 }
391 _ => 0.0,
392 })
393 })
394 .unwrap_or(0.0);
395 let extra = with_host(|h| {
396 let mut m = IndexMap::new();
397 m.insert("name".to_string(), h.new_str(name));
398 m.insert("lastModified".to_string(), Value::Float(last_modified));
399 m
400 });
401 Ok(build_blob("File", &bytes, &typ, extra))
402}
403
404pub const BLOB_METHODS: &[&str] = &["text", "arrayBuffer", "bytes", "slice"];
406
407pub fn blob_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
412 let bytes = bytes_of(recv);
413 match method {
414 "text" => {
415 let s = String::from_utf8_lossy(&bytes).into_owned();
416 let sv = with_host(|h| h.new_str(s));
417 Ok(crate::host::promise_of(&sv))
418 }
419 "arrayBuffer" | "bytes" => {
420 let buf = from_bytes(&bytes);
421 Ok(crate::host::promise_of(&buf))
422 }
423 "slice" => {
424 let (s, e) = slice_bounds(args, bytes.len());
425 let typ = if args.len() > 2 {
426 arg_str(args, 2)
427 } else {
428 String::new()
429 };
430 Ok(build_blob("Blob", &bytes[s..e], &typ, IndexMap::new()))
431 }
432 _ => Err(crate::host::type_error(&format!(
433 "blob.{method} is not a function"
434 ))),
435 }
436}
437
438pub fn share_array_buffer(ab: &Value, off: usize, len: usize) -> Value {
441 let store = crate::stdlib::typedarray::buffer_store(ab);
442 with_host(|h| {
443 let mut m = IndexMap::new();
444 m.insert("@@native".into(), h.new_str("Buffer"));
445 m.insert(
446 "@@bytes".into(),
447 store.unwrap_or_else(|| h.new_array(Vec::new())),
448 );
449 m.insert("@@buffer".into(), ab.clone());
450 m.insert("buffer".into(), ab.clone());
451 m.insert("length".into(), Value::Float(len as f64));
452 m.insert("byteLength".into(), Value::Float(len as f64));
453 m.insert("byteOffset".into(), Value::Float(off as f64));
454 m.insert("BYTES_PER_ELEMENT".into(), Value::Float(1.0));
455 let obj = h.new_object(m);
456 h.ensure_native_protos();
457 if let Some(p) = h.native_proto("Buffer") {
458 h.set_proto(&obj, p);
459 }
460 for k in [
461 "buffer",
462 "length",
463 "byteLength",
464 "byteOffset",
465 "BYTES_PER_ELEMENT",
466 ] {
467 h.hide_prop(&obj, k);
468 }
469 obj
470 })
471}
472
473pub fn from_bytes(bytes: &[u8]) -> Value {
479 let arr = with_host(|h| h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect()));
480 let ab = crate::stdlib::typedarray::array_buffer_over(arr);
481 share_array_buffer(&ab, 0, bytes.len())
482}
483
484const POOL_PADDING: usize = 64;
500
501fn pool_size_value() -> f64 {
503 let set = with_host(|h| h.builtin_static("Buffer", "poolSize"));
504 match set {
505 Some(v) => with_host(|h| h.to_number(&v)),
506 None => 65536.0,
507 }
508}
509
510fn pool_half() -> usize {
512 let n = pool_size_value();
513 let u = if n.is_finite() {
514 n.trunc().rem_euclid(4294967296.0) as u32
515 } else {
516 0
517 };
518 (u >> 1) as usize
519}
520
521fn create_pool() {
523 let size = pool_size_value().max(0.0) as usize;
524 let arr = with_host(|h| h.new_array(vec![Value::Float(0.0); size + POOL_PADDING]));
525 let ab = crate::stdlib::typedarray::array_buffer_over(arr);
526 crate::stdlib::typedarray::mark_untransferable(&ab);
527 with_host(|h| h.buffer_pool = Some((ab, size, 0)));
528}
529
530fn pool_slice(reserve: usize, bytes: &[u8]) -> Value {
534 let fits = with_host(
535 |h| matches!(h.buffer_pool, Some((_, size, off)) if reserve <= size - off.min(size)),
536 );
537 if !fits {
538 create_pool();
539 }
540 let Some((ab, size, off)) = with_host(|h| h.buffer_pool.clone()) else {
541 return from_bytes(bytes);
542 };
543 if let Some(store) = crate::stdlib::typedarray::buffer_store(&ab) {
544 with_host(|h| {
545 if let Some(JsObj::Array(items)) = h.get_mut(&store) {
546 for (i, b) in bytes.iter().enumerate() {
547 items[off + i] = Value::Float(*b as f64);
548 }
549 }
550 });
551 }
552 let buf = share_array_buffer(&ab, off, bytes.len());
553 let next = (off + bytes.len() + 7) & !7;
555 with_host(|h| h.buffer_pool = Some((ab, size, next)));
556 buf
557}
558
559pub fn pooled(bytes: &[u8]) -> Value {
562 if bytes.is_empty() || bytes.len() >= pool_half() {
563 return from_bytes(bytes);
564 }
565 pool_slice(bytes.len(), bytes)
566}
567
568fn pooled_string(s: &str, enc: &str) -> Value {
572 let bytes = decode_str(s, enc);
573 if s.is_empty() {
574 return from_bytes(&bytes);
575 }
576 let max = pool_half();
577 let units = s.encode_utf16().count();
578 if units >= max {
579 return from_bytes(&bytes);
580 }
581 let mut estimate = units * 4;
582 if estimate >= max {
583 estimate = bytes.len();
584 }
585 if estimate >= max {
586 return from_bytes(&bytes);
587 }
588 pool_slice(estimate, &bytes)
589}
590
591fn window(recv: &Value) -> (usize, usize) {
598 with_host(|h| match h.get(recv) {
599 Some(JsObj::Object(p)) => window_h(h, p),
600 _ => (0, 0),
601 })
602}
603
604pub fn window_h(h: &crate::host::JsHost, p: &IndexMap<String, Value>) -> (usize, usize) {
606 let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0) as usize;
607 let store = match p.get("@@bytes").and_then(|v| h.get(v)) {
608 Some(JsObj::Array(items)) => items.len(),
609 _ => 0,
610 };
611 let len = p
612 .get("length")
613 .map(|l| h.to_number(l) as usize)
614 .unwrap_or(store);
615 (off.min(store), len.min(store.saturating_sub(off)))
616}
617
618pub fn window_bytes_h(h: &crate::host::JsHost, p: &IndexMap<String, Value>) -> Vec<u8> {
623 let (off, len) = window_h(h, p);
624 match p.get("@@bytes").and_then(|v| h.get(v)) {
625 Some(JsObj::Array(items)) => items[off..off + len]
626 .iter()
627 .map(|v| h.to_number(v) as u8)
628 .collect(),
629 _ => Vec::new(),
630 }
631}
632
633fn bytes_of(recv: &Value) -> Vec<u8> {
634 with_host(|h| match h.get(recv) {
635 Some(JsObj::Object(p)) => window_bytes_h(h, p),
636 _ => Vec::new(),
637 })
638}
639
640fn bytes_handle(recv: &Value) -> Option<Value> {
642 with_host(|h| match h.get(recv) {
643 Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
644 _ => None,
645 })
646}
647
648pub fn byte_get(recv: &Value, index: &str) -> Value {
655 let i: usize = match index.parse() {
656 Ok(i) => i,
657 Err(_) => return Value::Undef,
658 };
659 let arr = match bytes_handle(recv) {
660 Some(a) => a,
661 None => return Value::Undef,
662 };
663 let (off, len) = window(recv);
664 if i >= len {
665 return Value::Undef;
666 }
667 with_host(|h| match h.get(&arr) {
668 Some(JsObj::Array(items)) => match items.get(off + i) {
669 Some(v) => Value::Float(h.to_number(v)),
670 None => Value::Undef,
671 },
672 _ => Value::Undef,
673 })
674}
675
676pub fn byte_set(recv: &Value, index: &str, val: &Value) -> bool {
682 if super::native_tag(recv).as_deref() != Some("Buffer") {
683 return false;
684 }
685 let i: usize = match index.parse() {
686 Ok(i) => i,
687 Err(_) => return false,
688 };
689 let arr = match bytes_handle(recv) {
690 Some(a) => a,
691 None => return false,
692 };
693 let b = with_host(|h| h.to_number(val)) as i64 as u8;
694 let (off, len) = window(recv);
697 if i >= len {
698 return true;
699 }
700 with_host(|h| {
701 if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
702 if let Some(slot) = items.get_mut(off + i) {
704 *slot = Value::Float(b as f64);
705 }
706 }
707 });
708 true
709}
710
711const K_MAX_LENGTH: f64 = 9_007_199_254_740_991.0;
713
714fn validate_size(args: &[Value]) -> Result<usize, String> {
721 let v = args.first().cloned().unwrap_or(Value::Undef);
722 if with_host(|h| h.type_of(&v)) != "number" {
723 return Err(crate::host::invalid_arg_type(
724 "size", "argument", "number", &v,
725 ));
726 }
727 let n = with_host(|h| h.to_number(&v));
728 if n.is_nan() || !(0.0..=K_MAX_LENGTH).contains(&n) {
729 return Err(crate::host::coded_error(
730 "RangeError",
731 "ERR_OUT_OF_RANGE",
732 &format!(
733 "The value of \"size\" is out of range. It must be >= 0 && <= {}. Received {}",
734 crate::host::fmt_number(K_MAX_LENGTH),
735 out_of_range_received(n)
736 ),
737 ));
738 }
739 Ok(n as usize)
740}
741
742pub(crate) fn out_of_range_received(n: f64) -> String {
747 let shown = crate::host::fmt_number(n);
748 if n.fract() != 0.0 || n.abs() <= 4_294_967_296.0 {
749 return shown;
750 }
751 let start = usize::from(shown.starts_with('-'));
752 let mut i = shown.len();
753 let mut groups = String::new();
754 while i >= start + 4 {
755 groups = format!("_{}{groups}", &shown[i - 3..i]);
756 i -= 3;
757 }
758 format!("{}{groups}", &shown[..i])
759}
760
761pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
762 Some(match method {
763 "from" => from(args),
764 "copyBytesFrom" => copy_bytes_from(args),
765 "alloc" => {
766 let n = match validate_size(args) {
767 Ok(n) => n,
768 Err(e) => return Some(Err(e)),
769 };
770 let pat = if args.len() > 1 {
773 let enc = if args.len() > 2 {
774 arg_str(args, 2)
775 } else {
776 "utf8".into()
777 };
778 fill_pattern(args, 1, &enc)
779 } else {
780 vec![0]
781 };
782 let bytes: Vec<u8> = if pat.is_empty() {
783 vec![0u8; n]
784 } else {
785 (0..n).map(|i| pat[i % pat.len()]).collect()
786 };
787 Ok(from_bytes(&bytes))
788 }
789 "allocUnsafe" => validate_size(args).map(|n| pooled(&vec![0u8; n])),
792 "allocUnsafeSlow" => validate_size(args).map(|n| from_bytes(&vec![0u8; n])),
793 "concat" => concat(args),
794 "of" => Ok(from_bytes(
798 &args
799 .iter()
800 .map(|v| crate::host::with_host(|h| h.to_number(v)) as u8)
801 .collect::<Vec<u8>>(),
802 )),
803 "isEncoding" => Ok(Value::Bool(matches!(
807 super::arg_str(args, 0).to_ascii_lowercase().as_str(),
808 "utf8"
809 | "utf-8"
810 | "ucs2"
811 | "ucs-2"
812 | "utf16le"
813 | "utf-16le"
814 | "latin1"
815 | "binary"
816 | "base64"
817 | "base64url"
818 | "hex"
819 | "ascii"
820 ))),
821 "compare" => {
823 let a = match uint8_arg(args.first(), "buf1") {
824 Ok(b) => b,
825 Err(e) => return Some(Err(e)),
826 };
827 let b = match uint8_arg(args.get(1), "buf2") {
828 Ok(b) => b,
829 Err(e) => return Some(Err(e)),
830 };
831 Ok(ordering_value(a.cmp(&b)))
832 }
833 "isBuffer" => Ok(Value::Bool(
834 super::native_tag(&args.first().cloned().unwrap_or(Value::Undef)).as_deref()
835 == Some("Buffer"),
836 )),
837 "byteLength" => {
838 if let Some(n) = view_byte_length(&args.first().cloned().unwrap_or(Value::Undef)) {
841 return Some(Ok(Value::Float(n)));
842 }
843 let enc = args
844 .get(1)
845 .map(|_| arg_str(args, 1))
846 .unwrap_or_else(|| "utf8".into());
847 Ok(Value::Float(
848 decode_str(&arg_str(args, 0), &enc).len() as f64
849 ))
850 }
851 _ => return None,
852 })
853}
854
855pub fn view_bytes(v: &Value) -> Option<Vec<u8>> {
877 match super::native_tag(v).as_deref() {
878 Some("DataView") => {
884 let n = with_host(|h| match h.get(v) {
885 Some(JsObj::Object(p)) => p.get("byteLength").map(|l| h.to_number(l) as usize),
886 _ => None,
887 })
888 .unwrap_or(0);
889 crate::stdlib::typedarray::view_bytes(v, 0, n)
890 }
891 Some("TypedArray") => crate::stdlib::typedarray::raw_view_bytes(v),
894 Some("Buffer") | Some("ArrayBuffer") => bytes_like(v),
895 _ => None,
896 }
897}
898
899pub fn bytes_like(v: &Value) -> Option<Vec<u8>> {
900 if let Some(elems) = crate::stdlib::typedarray::elems_of(v) {
902 return Some(elems.iter().map(|x| *x as i64 as u8).collect());
903 }
904 if super::native_tag(v).as_deref() == Some("ArrayBuffer") {
907 return Some(crate::stdlib::typedarray::buffer_bytes_snapshot(v).unwrap_or_default());
908 }
909 with_host(|h| match h.get(v) {
911 Some(JsObj::Array(items)) => {
912 Some(items.iter().map(|x| h.to_number(x) as i64 as u8).collect())
913 }
914 _ => None,
915 })
916}
917
918fn view_byte_length(v: &Value) -> Option<f64> {
922 match super::native_tag(v).as_deref() {
923 Some("Buffer") | Some("TypedArray") | Some("ArrayBuffer") => {
924 with_host(|h| match h.get(v) {
925 Some(JsObj::Object(p)) => p.get("byteLength").map(|b| h.to_number(b)),
926 _ => None,
927 })
928 }
929 _ => None,
930 }
931}
932
933fn from(args: &[Value]) -> Result<Value, String> {
934 let v = args.first().cloned().unwrap_or(Value::Undef);
935 if super::native_tag(&v).as_deref() == Some("ArrayBuffer") {
939 let total = crate::stdlib::typedarray::buffer_byte_length(&v);
940 let off = (super::arg_num(args, 1).max(0.0) as usize).min(total);
941 let len = match args.get(2) {
942 Some(Value::Undef) | None => total - off,
943 Some(_) => (super::arg_num(args, 2).max(0.0) as usize).min(total - off),
944 };
945 return Ok(share_array_buffer(&v, off, len));
946 }
947 if let Some(bytes) = bytes_like(&v) {
949 return Ok(pooled(&bytes));
950 }
951 if with_host(|h| h.as_str(&v)).is_some() || matches!(v, Value::Str(_)) {
953 let enc = if args.len() > 1 {
954 arg_str(args, 1)
955 } else {
956 "utf8".into()
957 };
958 return Ok(pooled_string(&arg_str(args, 0), &enc));
959 }
960 if super::native_tag(&v).as_deref() == Some("DataView") {
963 return Ok(from_bytes(&[]));
964 }
965 if matches!(v, Value::Obj(_)) {
969 let len = crate::builtins::get_property(&v, "length").unwrap_or(Value::Undef);
970 if !matches!(len, Value::Undef) {
971 let n = with_host(|h| h.to_number(&len));
972 if n.is_finite() && n >= 0.0 {
973 let n = n as usize;
974 let mut out = Vec::with_capacity(n);
975 for i in 0..n {
976 let e =
977 crate::builtins::get_property(&v, &i.to_string()).unwrap_or(Value::Undef);
978 let b = with_host(|h| h.to_number(&e));
979 out.push(if b.is_finite() { b as i64 as u8 } else { 0 });
980 }
981 return Ok(pooled(&out));
982 }
983 }
984 let ty = crate::builtins::get_property(&v, "type").unwrap_or(Value::Undef);
987 let data = crate::builtins::get_property(&v, "data").unwrap_or(Value::Undef);
988 if with_host(|h| h.as_str(&ty).is_some_and(|t| t == "Buffer"))
989 && with_host(|h| matches!(h.get(&data), Some(JsObj::Array(_))))
990 {
991 return Ok(pooled(&bytes_like(&data).unwrap_or_default()));
992 }
993 }
994 Err(crate::host::coded_error(
1000 "TypeError",
1001 "ERR_INVALID_ARG_TYPE",
1002 &format!(
1003 "The first argument must be of type string or an instance of \
1004Buffer, ArrayBuffer, or Array or an Array-like Object. Received {}",
1005 received_label(&v)
1006 ),
1007 ))
1008}
1009
1010fn received_label(v: &Value) -> String {
1013 if matches!(v, Value::Undef) {
1014 return "undefined".into();
1015 }
1016 if with_host(|h| h.is_null(v)) {
1017 return "null".into();
1018 }
1019 let ty = with_host(|h| h.type_of(v));
1020 if ty == "object" || ty == "function" {
1021 let ctor = with_host(|h| h.ctor_name(v));
1022 let ctor = if ctor.is_empty() {
1023 "Object".into()
1024 } else {
1025 ctor
1026 };
1027 return format!("an instance of {ctor}");
1028 }
1029 let shown = with_host(|h| h.inspect(v));
1030 format!("type {ty} ({shown})")
1031}
1032
1033fn concat(args: &[Value]) -> Result<Value, String> {
1034 let list_v = args.first().cloned().unwrap_or(Value::Undef);
1039 let list = match with_host(|h| h.get(&list_v).cloned()) {
1040 Some(JsObj::Array(items)) => items,
1041 _ => {
1042 return Err(crate::host::coded_error(
1043 "TypeError",
1044 "ERR_INVALID_ARG_TYPE",
1045 &format!(
1046 "The \"list\" argument must be an instance of Array. Received {}",
1047 super::received_desc(&list_v)
1048 ),
1049 ))
1050 }
1051 };
1052 if list.is_empty() {
1053 return Ok(from_bytes(&[]));
1054 }
1055 let length = match args.get(1) {
1056 None | Some(Value::Undef) => None,
1057 Some(v) => Some(validate_offset(v, "length")?),
1058 };
1059 let mut out = Vec::new();
1060 for (i, b) in list.iter().enumerate() {
1061 if super::util_types::ta_kind(b).as_deref() != Some("Uint8Array") {
1062 return Err(crate::host::coded_error(
1063 "TypeError",
1064 "ERR_INVALID_ARG_TYPE",
1065 &format!(
1066 "The \"list[{i}]\" argument must be an instance of Buffer or Uint8Array. Received {}",
1067 super::received_desc(b)
1068 ),
1069 ));
1070 }
1071 out.extend(bytes_like(b).unwrap_or_default());
1072 }
1073 if let Some(n) = length {
1074 out.resize(n, 0);
1075 }
1076 Ok(pooled(&out))
1077}
1078
1079fn validate_offset(v: &Value, name: &str) -> Result<usize, String> {
1082 validate_offset_in(v, name, K_MAX_LENGTH)
1083}
1084
1085fn validate_offset_in(v: &Value, name: &str, max: f64) -> Result<usize, String> {
1088 if with_host(|h| h.type_of(v)) != "number" {
1089 return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
1090 }
1091 let n = with_host(|h| h.to_number(v));
1092 let out_of_range = |must: String| {
1093 crate::host::coded_error(
1094 "RangeError",
1095 "ERR_OUT_OF_RANGE",
1096 &format!(
1097 "The value of \"{name}\" is out of range. It must be {must}. Received {}",
1098 out_of_range_received(n)
1099 ),
1100 )
1101 };
1102 if n.is_nan() || n.fract() != 0.0 {
1103 return Err(out_of_range("an integer".to_string()));
1104 }
1105 if !(0.0..=max).contains(&n) {
1106 return Err(out_of_range(format!(
1107 ">= 0 && <= {}",
1108 crate::host::fmt_number(max)
1109 )));
1110 }
1111 Ok(n as usize)
1112}
1113
1114fn uint8_arg(v: Option<&Value>, name: &str) -> Result<Vec<u8>, String> {
1118 let v = v.cloned().unwrap_or(Value::Undef);
1119 if super::util_types::ta_kind(&v).as_deref() != Some("Uint8Array") {
1120 return Err(crate::host::coded_error(
1121 "TypeError",
1122 "ERR_INVALID_ARG_TYPE",
1123 &format!(
1124 "The \"{name}\" argument must be an instance of Buffer or Uint8Array. Received {}",
1125 super::received_desc(&v)
1126 ),
1127 ));
1128 }
1129 Ok(view_bytes(&v).unwrap_or_default())
1130}
1131
1132fn ordering_value(o: std::cmp::Ordering) -> Value {
1134 Value::Float(match o {
1135 std::cmp::Ordering::Less => -1.0,
1136 std::cmp::Ordering::Equal => 0.0,
1137 std::cmp::Ordering::Greater => 1.0,
1138 })
1139}
1140
1141pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1143 let bytes = bytes_of(recv);
1144 match method {
1145 "toString" => {
1148 let enc = match args.first() {
1149 None | Some(Value::Undef) => "utf8".into(),
1150 _ => arg_str(args, 0),
1151 };
1152 let len = bytes.len();
1153 let clamp = |i: usize| -> usize {
1154 let n = super::arg_num(args, i);
1155 if n.is_nan() {
1156 0
1157 } else {
1158 n.clamp(0.0, len as f64) as usize
1159 }
1160 };
1161 let start = if args.len() > 1 { clamp(1) } else { 0 };
1162 let end = if args.len() > 2 { clamp(2) } else { len };
1163 let slice = if start < end {
1165 &bytes[start..end]
1166 } else {
1167 &[][..]
1168 };
1169 Ok(with_host(|h| h.new_str(encode_bytes(slice, &enc))))
1170 }
1171 "toJSON" => Ok(with_host(|h| {
1172 let data = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
1173 let mut m = IndexMap::new();
1174 m.insert("type".into(), h.new_str("Buffer"));
1175 m.insert("data".into(), data);
1176 h.new_object(m)
1177 })),
1178 "equals" => {
1179 let other = uint8_arg(args.first(), "otherBuffer")?;
1182 Ok(Value::Bool(bytes == other))
1183 }
1184 "slice" | "subarray" => {
1187 let (s, e) = slice_bounds(args, bytes.len());
1188 let (off, _) = window(recv);
1189 let ab = with_host(|h| match h.get(recv) {
1190 Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
1191 _ => None,
1192 });
1193 Ok(match ab {
1194 Some(ab) => share_array_buffer(&ab, off + s, e - s),
1195 None => from_bytes(&bytes[s..e]),
1196 })
1197 }
1198 "readUInt8" => {
1199 let i = read_offset(args, 1, bytes.len())?;
1200 Ok(Value::Float(bytes[i] as f64))
1201 }
1202 "includes" | "indexOf" | "lastIndexOf" => {
1206 let len = bytes.len();
1207 let last = method == "lastIndexOf";
1208 let (from, enc) = match args.get(1) {
1210 None | Some(Value::Undef) => (None, arg_str(args, 2)),
1211 Some(v) if with_host(|h| h.as_str(v)).is_some() => (None, arg_str(args, 1)),
1212 _ => (Some(super::arg_num(args, 1)), arg_str(args, 2)),
1213 };
1214 let enc = if enc.is_empty() { "utf8".into() } else { enc };
1215 let target = args.first().cloned().unwrap_or(Value::Undef);
1220 let needle = match with_host(|h| h.type_of(&target)) {
1221 "number" => {
1222 let n = super::arg_num(args, 0);
1223 vec![crate::host::to_int32(n) as u32 as u8]
1224 }
1225 "string" => decode_str(&arg_str(args, 0), &enc),
1226 _ if super::util_types::ta_kind(&target).as_deref() == Some("Uint8Array") => {
1227 view_bytes(&target).unwrap_or_default()
1228 }
1229 _ => {
1230 return Err(crate::host::coded_error(
1231 "TypeError",
1232 "ERR_INVALID_ARG_TYPE",
1233 &format!(
1234 "The \"value\" argument must be one of type number or string or an instance of Buffer or Uint8Array. Received {}",
1235 super::received_desc(&target)
1236 ),
1237 ))
1238 }
1239 };
1240 let from = from.map(|n| {
1243 if n.is_nan() {
1244 0
1245 } else if n < 0.0 {
1246 (len as f64 + n).max(0.0) as usize
1247 } else {
1248 (n as usize).min(len)
1249 }
1250 });
1251 let pos = if needle.is_empty() {
1253 Some(from.unwrap_or(if last { len } else { 0 }).min(len))
1254 } else if last {
1255 let hi = (from.unwrap_or(len) + needle.len()).min(len);
1258 bytes[..hi]
1259 .windows(needle.len())
1260 .rposition(|w| w == needle.as_slice())
1261 } else {
1262 let lo = from.unwrap_or(0);
1263 bytes[lo..]
1264 .windows(needle.len())
1265 .position(|w| w == needle.as_slice())
1266 .map(|p| p + lo)
1267 };
1268 if method == "includes" {
1269 Ok(Value::Bool(pos.is_some()))
1270 } else {
1271 Ok(Value::Float(pos.map(|p| p as f64).unwrap_or(-1.0)))
1272 }
1273 }
1274 "compare" => {
1280 let target = uint8_arg(args.first(), "target")?;
1281 let bound = |i: usize, name: &str, default: usize, max: f64| match args.get(i) {
1282 None | Some(Value::Undef) => Ok(default),
1283 Some(v) => validate_offset_in(v, name, max),
1284 };
1285 let t_start = bound(1, "targetStart", 0, K_MAX_LENGTH)?;
1286 let t_end = bound(2, "targetEnd", target.len(), target.len() as f64)?;
1287 let s_start = bound(3, "sourceStart", 0, K_MAX_LENGTH)?;
1288 let s_end = bound(4, "sourceEnd", bytes.len(), bytes.len() as f64)?;
1289 if s_start >= s_end {
1290 return Ok(Value::Float(if t_start >= t_end { 0.0 } else { -1.0 }));
1291 }
1292 if t_start >= t_end {
1293 return Ok(Value::Float(1.0));
1294 }
1295 Ok(ordering_value(
1296 bytes[s_start..s_end].cmp(&target[t_start..t_end]),
1297 ))
1298 }
1299 "readUInt16BE" => {
1301 let i = read_offset(args, 2, bytes.len())?;
1302 let v = ((bytes[i] as u16) << 8) | bytes[i + 1] as u16;
1303 Ok(Value::Float(v as f64))
1304 }
1305 "readUInt16LE" => {
1306 let i = read_offset(args, 2, bytes.len())?;
1307 let v = (bytes[i] as u16) | ((bytes[i + 1] as u16) << 8);
1308 Ok(Value::Float(v as f64))
1309 }
1310 "readUInt32BE" | "readUInt32LE" | "readInt32BE" | "readInt32LE" => {
1313 let i = read_offset(args, 4, bytes.len())?;
1314 let at = |k: usize| bytes[i + k] as u32;
1315 let v = if method.ends_with("BE") {
1316 (at(0) << 24) | (at(1) << 16) | (at(2) << 8) | at(3)
1317 } else {
1318 at(0) | (at(1) << 8) | (at(2) << 16) | (at(3) << 24)
1319 };
1320 Ok(Value::Float(if method.starts_with("readInt") {
1321 v as i32 as f64
1322 } else {
1323 v as f64
1324 }))
1325 }
1326 "readInt8" => {
1327 let i = read_offset(args, 1, bytes.len())?;
1328 Ok(Value::Float(bytes[i] as i8 as f64))
1329 }
1330 "readInt16BE" | "readInt16LE" => {
1331 let i = read_offset(args, 2, bytes.len())?;
1332 let at = |k: usize| bytes[i + k] as u16;
1333 let v = if method.ends_with("BE") {
1334 (at(0) << 8) | at(1)
1335 } else {
1336 at(0) | (at(1) << 8)
1337 };
1338 Ok(Value::Float(v as i16 as f64))
1339 }
1340 "at" => {
1342 let i = super::arg_num(args, 0);
1343 let idx = if i < 0.0 { i + bytes.len() as f64 } else { i };
1344 Ok(match bytes.get(idx.max(-1.0) as usize) {
1345 Some(b) if idx >= 0.0 => Value::Float(*b as f64),
1346 _ => Value::Undef,
1347 })
1348 }
1349 "values" | "keys" | "entries" | "@@iterator" => {
1354 if crate::stdlib::typedarray::view_detached(recv) {
1357 let name = if method == "@@iterator" {
1358 "values"
1359 } else {
1360 method
1361 };
1362 return Err(crate::stdlib::typedarray::detached_error(
1363 "%TypedArray%.prototype",
1364 name,
1365 false,
1366 ));
1367 }
1368 let items: Vec<Value> = with_host(|h| match method {
1369 "keys" => (0..bytes.len()).map(|i| Value::Float(i as f64)).collect(),
1370 "values" | "@@iterator" => bytes.iter().map(|b| Value::Float(*b as f64)).collect(),
1371 _ => bytes
1372 .iter()
1373 .enumerate()
1374 .map(|(i, b)| {
1375 h.new_array(vec![Value::Float(i as f64), Value::Float(*b as f64)])
1376 })
1377 .collect(),
1378 });
1379 Ok(with_host(|h| {
1380 h.alloc_iter(JsObj::Iter {
1381 items,
1382 idx: 0,
1383 array: None,
1384 brand: Some("Array Iterator"),
1385 })
1386 }))
1387 }
1388 "readFloatBE" | "readFloatLE" => {
1391 let i = read_offset(args, 4, bytes.len())?;
1392 let mut raw = [0u8; 4];
1393 raw.copy_from_slice(&bytes[i..i + 4]);
1394 if method.ends_with("LE") {
1395 raw.reverse();
1396 }
1397 Ok(Value::Float(f32::from_be_bytes(raw) as f64))
1398 }
1399 "readDoubleBE" | "readDoubleLE" => {
1400 let i = read_offset(args, 8, bytes.len())?;
1401 let mut raw = [0u8; 8];
1402 raw.copy_from_slice(&bytes[i..i + 8]);
1403 if method.ends_with("LE") {
1404 raw.reverse();
1405 }
1406 Ok(Value::Float(f64::from_be_bytes(raw)))
1407 }
1408 "writeFloatBE" | "writeFloatLE" => {
1409 let mut raw = (super::arg_num(args, 0) as f32).to_be_bytes();
1410 if method.ends_with("LE") {
1411 raw.reverse();
1412 }
1413 let off = write_offset(args, 4, bytes.len())?;
1414 store_bytes(recv, &bytes, off, &raw)?;
1415 Ok(Value::Float((off + 4) as f64))
1416 }
1417 "writeDoubleBE" | "writeDoubleLE" => {
1418 let mut raw = super::arg_num(args, 0).to_be_bytes();
1419 if method.ends_with("LE") {
1420 raw.reverse();
1421 }
1422 let off = write_offset(args, 8, bytes.len())?;
1423 store_bytes(recv, &bytes, off, &raw)?;
1424 Ok(Value::Float((off + 8) as f64))
1425 }
1426 "readBigInt64BE" | "readBigInt64LE" | "readBigUInt64BE" | "readBigUInt64LE" => {
1429 let i = read_offset(args, 8, bytes.len())?;
1430 let mut raw = [0u8; 8];
1431 raw.copy_from_slice(&bytes[i..i + 8]);
1432 if method.ends_with("LE") {
1433 raw.reverse();
1434 }
1435 let n = if method.starts_with("readBigInt") {
1436 num_bigint::BigInt::from(i64::from_be_bytes(raw))
1437 } else {
1438 num_bigint::BigInt::from(u64::from_be_bytes(raw))
1439 };
1440 Ok(with_host(|h| h.alloc(JsObj::BigInt(n))))
1441 }
1442 "writeBigInt64BE" | "writeBigInt64LE" | "writeBigUInt64BE" | "writeBigUInt64LE" => {
1443 let v = args.first().cloned().unwrap_or(Value::Undef);
1444 let n = big_write_value(&v, method.starts_with("writeBigInt"))?;
1445 let bits = num_traits::ToPrimitive::to_i64(&n)
1448 .map(|x| x as u64)
1449 .or_else(|| num_traits::ToPrimitive::to_u64(&n))
1450 .unwrap_or(0);
1451 let mut raw = bits.to_be_bytes();
1452 if method.ends_with("LE") {
1453 raw.reverse();
1454 }
1455 let off = write_offset(args, 8, bytes.len())?;
1456 store_bytes(recv, &bytes, off, &raw)?;
1457 Ok(Value::Float((off + 8) as f64))
1458 }
1459 "readIntBE" | "readIntLE" | "readUIntBE" | "readUIntLE" => {
1462 let width = variable_byte_length(args.get(1))?;
1463 let off = read_offset(args, width, bytes.len())?;
1464 let mut acc: u64 = 0;
1465 for k in 0..width {
1466 let b = if method.ends_with("BE") {
1467 bytes[off + k]
1468 } else {
1469 bytes[off + width - 1 - k]
1470 };
1471 acc = (acc << 8) | b as u64;
1472 }
1473 let signed = method.starts_with("readInt");
1474 let out = if signed {
1475 let shift = 64 - (width * 8);
1477 ((acc << shift) as i64 >> shift) as f64
1478 } else {
1479 acc as f64
1480 };
1481 Ok(Value::Float(out))
1482 }
1483 "writeIntBE" | "writeIntLE" | "writeUIntBE" | "writeUIntLE" | "writeInt8"
1488 | "writeUInt8" | "writeInt16BE" | "writeInt16LE" | "writeUInt16BE" | "writeUInt16LE"
1489 | "writeInt32BE" | "writeInt32LE" | "writeUInt32BE" | "writeUInt32LE" => {
1490 let width = match method {
1491 "writeIntBE" | "writeIntLE" | "writeUIntBE" | "writeUIntLE" => {
1492 variable_byte_length(args.get(2))?
1493 }
1494 "writeInt8" | "writeUInt8" => 1,
1495 m if m.contains("16") => 2,
1496 _ => 4,
1497 };
1498 let value = super::arg_num(args, 0);
1499 let bits = (width * 8) as i32;
1500 let (min, max) = if method.starts_with("writeInt") {
1501 (-(2f64.powi(bits - 1)), 2f64.powi(bits - 1) - 1.0)
1502 } else {
1503 (0.0, 2f64.powi(bits) - 1.0)
1504 };
1505 check_int_value(value, min, max, width - 1)?;
1506 let off = write_offset(args, width, bytes.len())?;
1507 let val = value as i64 as u64;
1509 let mut raw: Vec<u8> = (0..width)
1510 .map(|k| (val >> (8 * (width - 1 - k))) as u8)
1511 .collect();
1512 if method.ends_with("LE") {
1513 raw.reverse();
1514 }
1515 store_bytes(recv, &bytes, off, &raw)?;
1516 Ok(Value::Float((off + width) as f64))
1517 }
1518 "write" => {
1522 let mut b = bytes.clone();
1523 let Some((off, max, enc)) = write_args(args, b.len()) else {
1524 return Err(crate::host::range_error(&format!(
1525 "The value of \"offset\" is out of range. It must be >= 0 && <= {}. Received {}",
1526 b.len(),
1527 super::arg_num(args, 1)
1528 )));
1529 };
1530 let src = truncate_chars(&arg_str(args, 0), &enc, max);
1531 let n = src.len().min(b.len().saturating_sub(off));
1532 b[off..off + n].copy_from_slice(&src[..n]);
1533 set_bytes(recv, &b);
1534 Ok(Value::Float(n as f64))
1535 }
1536 "swap16" | "swap32" | "swap64" => {
1540 let group = match method {
1541 "swap16" => 2,
1542 "swap32" => 4,
1543 _ => 8,
1544 };
1545 if bytes.len() % group != 0 {
1546 return Err(crate::host::coded_error(
1547 "RangeError",
1548 "ERR_INVALID_BUFFER_SIZE",
1549 &format!("Buffer size must be a multiple of {}-bits", group * 8),
1550 ));
1551 }
1552 let mut b = bytes.clone();
1553 for c in b.chunks_mut(group) {
1554 c.reverse();
1555 }
1556 set_bytes(recv, &b);
1557 Ok(recv.clone())
1558 }
1559 "fill" => {
1565 let mut b = bytes.clone();
1566 let len = b.len();
1567 let (start, end, enc) = if arg_is_str(args, 1) {
1568 (0, len, arg_str(args, 1))
1569 } else if arg_is_str(args, 2) {
1570 let s = (super::arg_num(args, 1).max(0.0) as usize).min(len);
1571 (s, len, arg_str(args, 2))
1572 } else {
1573 let s = if args.len() > 1 {
1574 (super::arg_num(args, 1).max(0.0) as usize).min(len)
1575 } else {
1576 0
1577 };
1578 let e = if args.len() > 2 {
1579 (super::arg_num(args, 2).max(0.0) as usize).min(len)
1580 } else {
1581 len
1582 };
1583 let enc = if args.len() > 3 {
1584 arg_str(args, 3)
1585 } else {
1586 "utf8".into()
1587 };
1588 (s, e, enc)
1589 };
1590 let pat = fill_pattern(args, 0, &enc);
1591 if !pat.is_empty() {
1592 for (k, slot) in b[start..end.max(start)].iter_mut().enumerate() {
1593 *slot = pat[k % pat.len()];
1594 }
1595 }
1596 set_bytes(recv, &b);
1597 Ok(recv.clone())
1598 }
1599 "copy" => {
1601 let target = args.first().cloned().unwrap_or(Value::Undef);
1602 let mut tb = bytes_of(&target);
1603 let tstart = if args.len() > 1 {
1604 super::arg_num(args, 1).max(0.0) as usize
1605 } else {
1606 0
1607 };
1608 let sstart = if args.len() > 2 {
1609 super::arg_num(args, 2).max(0.0) as usize
1610 } else {
1611 0
1612 };
1613 let send = if args.len() > 3 {
1614 (super::arg_num(args, 3) as usize).min(bytes.len())
1615 } else {
1616 bytes.len()
1617 };
1618 let mut n = 0;
1619 for (k, &byte) in bytes[sstart..send.max(sstart)].iter().enumerate() {
1620 if tstart + k < tb.len() {
1621 tb[tstart + k] = byte;
1622 n += 1;
1623 }
1624 }
1625 set_bytes(&target, &tb);
1626 Ok(Value::Float(n as f64))
1627 }
1628 "set" => {
1631 let src = crate::stdlib::typedarray::set_source_bytes(args.first())?;
1632 let off = super::arg_num(args, 1);
1633 let off = if off.is_nan() { 0.0 } else { off.trunc() };
1634 if off < 0.0 || off + src.len() as f64 > bytes.len() as f64 {
1635 return Err(crate::host::range_error("offset is out of bounds"));
1636 }
1637 let offset = off as usize;
1638 let mut out = bytes.clone();
1639 out[offset..offset + src.len()].copy_from_slice(&src);
1640 set_bytes(recv, &out);
1641 Ok(Value::Undef)
1642 }
1643 _ if crate::stdlib::typedarray::PROTOTYPE_METHODS.contains(&method) => {
1651 crate::stdlib::typedarray::instance_call(recv, method, args)
1652 }
1653 _ => Err(crate::host::type_error(&format!(
1654 "buffer.{method} is not a function"
1655 ))),
1656 }
1657}
1658
1659fn fill_pattern(args: &[Value], idx: usize, enc: &str) -> Vec<u8> {
1661 match args.get(idx) {
1662 None => vec![0],
1663 Some(v) => {
1664 let is_str = matches!(v, Value::Str(_))
1665 || with_host(|h| matches!(h.get(v), Some(JsObj::Str(_))));
1666 if is_str {
1667 decode_str(&arg_str(args, idx), enc)
1668 } else {
1669 vec![super::arg_num(args, idx) as u8]
1670 }
1671 }
1672 }
1673}
1674
1675fn arg_is_str(args: &[Value], i: usize) -> bool {
1678 args.get(i)
1679 .is_some_and(|v| with_host(|h| h.as_str(v)).is_some())
1680}
1681
1682fn store_bytes(recv: &Value, bytes: &[u8], off: usize, out: &[u8]) -> Result<(), String> {
1690 if off + out.len() > bytes.len() {
1691 return Err(range_error_out_of_bounds());
1692 }
1693 let mut b = bytes.to_vec();
1694 b[off..off + out.len()].copy_from_slice(out);
1695 set_bytes(recv, &b);
1696 Ok(())
1697}
1698
1699fn range_error_out_of_bounds() -> String {
1700 crate::host::plain_coded_error(
1701 "RangeError",
1702 "ERR_OUT_OF_RANGE",
1703 "Attempt to access memory outside buffer bounds",
1704 )
1705}
1706
1707pub fn write_view(v: &Value, bytes: &[u8]) {
1712 match super::native_tag(v).as_deref() {
1713 Some("Buffer" | "ArrayBuffer") => set_bytes(v, bytes),
1714 Some("TypedArray" | "DataView") => {
1715 crate::stdlib::typedarray::write_view_bytes(v, 0, bytes);
1716 }
1717 _ => {}
1718 }
1719}
1720
1721fn set_bytes(recv: &Value, new: &[u8]) {
1722 let (off, _) = window(recv);
1723 with_host(|h| {
1724 let arr = match h.get(recv) {
1725 Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
1726 _ => None,
1727 };
1728 if let Some(a) = arr {
1729 if let Some(JsObj::Array(items)) = h.get_mut(&a) {
1730 for (i, b) in new.iter().enumerate() {
1733 if off + i < items.len() {
1734 items[off + i] = Value::Float(*b as f64);
1735 }
1736 }
1737 }
1738 }
1739 });
1740}
1741
1742fn slice_bounds(args: &[Value], len: usize) -> (usize, usize) {
1743 let norm = |n: f64| -> usize {
1744 if n < 0.0 {
1745 (len as f64 + n).max(0.0) as usize
1746 } else {
1747 (n as usize).min(len)
1748 }
1749 };
1750 let s = if args.is_empty() {
1751 0
1752 } else {
1753 norm(super::arg_num(args, 0))
1754 };
1755 let e = if args.len() < 2 {
1756 len
1757 } else {
1758 norm(super::arg_num(args, 1))
1759 };
1760 (s.min(e), e.max(s))
1761}
1762
1763pub(crate) fn decode_str(s: &str, enc: &str) -> Vec<u8> {
1771 match enc.to_ascii_lowercase().as_str() {
1772 "hex" => from_hex(s),
1773 "base64" | "base64url" => from_base64(s),
1774 "ascii" | "latin1" | "binary" => s.encode_utf16().map(|u| u as u8).collect(),
1779 "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
1782 s.encode_utf16().flat_map(|u| u.to_le_bytes()).collect()
1783 }
1784 _ => s.as_bytes().to_vec(),
1785 }
1786}
1787
1788pub(crate) fn encode_bytes(bytes: &[u8], enc: &str) -> String {
1789 match enc.to_ascii_lowercase().as_str() {
1790 "hex" => to_hex(bytes),
1791 "base64" => to_base64(bytes),
1792 "base64url" => super::to_base64url(bytes),
1793 "ascii" => bytes.iter().map(|b| (*b & 0x7f) as char).collect(),
1796 "latin1" | "binary" => bytes.iter().map(|b| *b as char).collect(),
1797 "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
1799 let units: Vec<u16> = bytes
1800 .chunks_exact(2)
1801 .map(|c| u16::from_le_bytes([c[0], c[1]]))
1802 .collect();
1803 crate::utf16::to_string_lossy(&units)
1804 }
1805 _ => String::from_utf8_lossy(bytes).into_owned(),
1806 }
1807}
1808
1809fn write_args(args: &[Value], len: usize) -> Option<(usize, usize, String)> {
1817 let num = |i: usize| super::arg_num(args, i);
1818 if args.len() < 2 {
1820 return Some((0, len, "utf8".into()));
1821 }
1822 if arg_is_str(args, 1) {
1823 return Some((0, len, arg_str(args, 1)));
1824 }
1825 let off = num(1);
1826 if !(0.0..=len as f64).contains(&off) {
1827 return None;
1828 }
1829 let off = off as usize;
1830 if args.len() < 3 {
1832 return Some((off, len - off, "utf8".into()));
1833 }
1834 if arg_is_str(args, 2) {
1835 return Some((off, len - off, arg_str(args, 2)));
1836 }
1837 let max = len - off;
1838 let n = (num(2).max(0.0) as usize).min(max);
1839 let enc = if args.len() > 3 {
1840 arg_str(args, 3)
1841 } else {
1842 "utf8".into()
1843 };
1844 Some((off, n, enc))
1845}
1846
1847fn truncate_chars(s: &str, enc: &str, max: usize) -> Vec<u8> {
1854 let bytes = decode_str(s, enc);
1855 if bytes.len() <= max {
1856 return bytes;
1857 }
1858 match enc.to_ascii_lowercase().as_str() {
1859 "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => bytes[..max - max % 2].to_vec(),
1860 "hex" | "base64" | "base64url" | "ascii" | "latin1" | "binary" => bytes[..max].to_vec(),
1861 _ => {
1862 let mut end = max;
1863 while end > 0 && (bytes[end] & 0xC0) == 0x80 {
1864 end -= 1;
1865 }
1866 bytes[..end].to_vec()
1867 }
1868 }
1869}
1870
1871fn read_offset(args: &[Value], size: usize, len: usize) -> Result<usize, String> {
1886 checked_offset(args.first(), size, len)
1887}
1888
1889fn big_write_value(v: &Value, signed: bool) -> Result<num_bigint::BigInt, String> {
1895 use num_bigint::BigInt;
1896 let (min, max_excl) = if signed {
1897 (
1898 -(BigInt::from(1u8) << 63usize),
1899 BigInt::from(1u8) << 63usize,
1900 )
1901 } else {
1902 (BigInt::from(0u8), BigInt::from(1u8) << 64usize)
1903 };
1904 let range = if signed {
1905 ">= -(2n ** 63n) and < 2n ** 63n"
1906 } else {
1907 ">= 0n and < 2n ** 64n"
1908 };
1909 let out_of_range = |received: String| {
1910 crate::host::coded_error(
1911 "RangeError",
1912 "ERR_OUT_OF_RANGE",
1913 &format!(
1914 "The value of \"value\" is out of range. It must be {range}. Received {received}"
1915 ),
1916 )
1917 };
1918 match with_host(|h| h.get(v).cloned()) {
1919 Some(JsObj::BigInt(b)) => {
1920 if b < min || b >= max_excl {
1921 let mut shown = b.to_string();
1922 if b.magnitude() > &num_bigint::BigUint::from(1u64 << 32) {
1923 shown = grouped_digits(&shown);
1924 }
1925 return Err(out_of_range(format!("{shown}n")));
1926 }
1927 Ok(b)
1928 }
1929 _ => {
1930 let n = with_host(|h| h.to_number(v));
1931 let (lo, hi) = if signed {
1932 (-(2f64.powi(63)), 2f64.powi(63))
1933 } else {
1934 (0.0, 2f64.powi(64))
1935 };
1936 if n < lo || n >= hi {
1937 return Err(out_of_range(out_of_range_received(n)));
1938 }
1939 Err(crate::host::type_error(
1940 "Cannot mix BigInt and other types, use explicit conversions",
1941 ))
1942 }
1943 }
1944}
1945
1946fn grouped_digits(shown: &str) -> String {
1948 let start = usize::from(shown.starts_with('-'));
1949 let mut i = shown.len();
1950 let mut groups = String::new();
1951 while i >= start + 4 {
1952 groups = format!("_{}{groups}", &shown[i - 3..i]);
1953 i -= 3;
1954 }
1955 format!("{}{groups}", &shown[..i])
1956}
1957
1958fn write_offset(args: &[Value], size: usize, len: usize) -> Result<usize, String> {
1959 checked_offset(args.get(1), size, len)
1960}
1961
1962fn check_int_value(value: f64, min: f64, max: f64, byte_len: usize) -> Result<(), String> {
1967 if !(value > max || value < min) {
1968 return Ok(());
1969 }
1970 let range = if byte_len > 3 {
1971 let bits = (byte_len + 1) * 8;
1972 if min == 0.0 {
1973 format!(">= 0 and < 2 ** {bits}")
1974 } else {
1975 format!(">= -(2 ** {}) and < 2 ** {}", bits - 1, bits - 1)
1976 }
1977 } else {
1978 format!(
1979 ">= {} and <= {}",
1980 crate::host::fmt_number(min),
1981 crate::host::fmt_number(max)
1982 )
1983 };
1984 Err(crate::host::coded_error(
1985 "RangeError",
1986 "ERR_OUT_OF_RANGE",
1987 &format!(
1988 "The value of \"value\" is out of range. It must be {range}. Received {}",
1989 out_of_range_received(value)
1990 ),
1991 ))
1992}
1993
1994fn variable_byte_length(v: Option<&Value>) -> Result<usize, String> {
1997 let v = v.cloned().unwrap_or(Value::Undef);
1998 if with_host(|h| h.type_of(&v)) != "number" {
1999 return Err(crate::host::invalid_arg_type(
2000 "byteLength",
2001 "argument",
2002 "number",
2003 &v,
2004 ));
2005 }
2006 let n = with_host(|h| h.to_number(&v));
2007 if n.fract() != 0.0 || n.is_nan() {
2008 return Err(crate::host::coded_error(
2009 "RangeError",
2010 "ERR_OUT_OF_RANGE",
2011 &format!(
2012 "The value of \"byteLength\" is out of range. It must be an integer. Received {}",
2013 crate::host::fmt_number(n)
2014 ),
2015 ));
2016 }
2017 if !(1.0..=6.0).contains(&n) {
2018 return Err(crate::host::coded_error(
2019 "RangeError",
2020 "ERR_OUT_OF_RANGE",
2021 &format!(
2022 "The value of \"byteLength\" is out of range. It must be >= 1 and <= 6. Received {}",
2023 crate::host::fmt_number(n)
2024 ),
2025 ));
2026 }
2027 Ok(n as usize)
2028}
2029
2030fn checked_offset(arg: Option<&Value>, size: usize, len: usize) -> Result<usize, String> {
2031 if let Some(v) = arg {
2033 if !matches!(v, Value::Undef) && with_host(|h| h.type_of(v)) != "number" {
2034 return Err(crate::host::invalid_arg_type(
2035 "offset", "argument", "number", v,
2036 ));
2037 }
2038 }
2039 if len < size {
2040 return Err(crate::host::coded_error(
2041 "RangeError",
2042 "ERR_BUFFER_OUT_OF_BOUNDS",
2043 "Attempt to access memory outside buffer bounds",
2044 ));
2045 }
2046 let max = len - size;
2047 let raw = match arg {
2048 None | Some(Value::Undef) => 0.0,
2049 Some(v) => with_host(|h| h.to_number(v)),
2050 };
2051 if raw.fract() != 0.0 || raw.is_nan() {
2054 return Err(crate::host::coded_error(
2055 "RangeError",
2056 "ERR_OUT_OF_RANGE",
2057 &format!(
2058 "The value of \"offset\" is out of range. It must be an integer. Received {}",
2059 crate::host::fmt_number(raw)
2060 ),
2061 ));
2062 }
2063 let off = raw;
2064 if off < 0.0 || off > max as f64 {
2065 return Err(crate::host::coded_error(
2066 "RangeError",
2067 "ERR_OUT_OF_RANGE",
2068 &format!(
2069 "The value of \"offset\" is out of range. It must be >= 0 and <= {max}. \
2070 Received {}",
2071 crate::host::fmt_number(raw)
2072 ),
2073 ));
2074 }
2075 Ok(off as usize)
2076}
2077
2078fn copy_bytes_from(args: &[Value]) -> Result<Value, String> {
2083 let view = args.first().cloned().unwrap_or(Value::Undef);
2084 let Some(kind) = super::util_types::ta_kind(&view) else {
2085 return Err(crate::host::coded_error(
2086 "TypeError",
2087 "ERR_INVALID_ARG_TYPE",
2088 &format!(
2089 "The \"view\" argument must be an instance of TypedArray. Received {}",
2090 super::received_desc(&view)
2091 ),
2092 ));
2093 };
2094 let bytes = view_bytes(&view).unwrap_or_default();
2095 let bpe = crate::stdlib::typedarray::bytes_per_element(&kind);
2096 let len = bytes.len() / bpe;
2097 if len == 0 {
2098 return Ok(from_bytes(&[]));
2099 }
2100 let arg = |i: usize| args.get(i).filter(|v| !matches!(v, Value::Undef));
2101 let offset = match arg(1) {
2102 Some(v) => super::validate_integer(v, "offset", 0.0)? as usize,
2103 None => 0,
2104 };
2105 if offset >= len {
2106 return Ok(from_bytes(&[]));
2107 }
2108 let end = match arg(2) {
2109 Some(v) => {
2110 (offset as f64 + super::validate_integer(v, "length", 0.0)?).min(len as f64) as usize
2111 }
2112 None => len,
2113 };
2114 Ok(pooled(&bytes[offset * bpe..end * bpe]))
2116}