deno_node 0.189.0

Node compatibility for Deno
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright 2018-2026 the Deno authors. MIT license.

use deno_core::convert::Uint8Array;
use deno_core::op2;
use deno_core::v8;
use deno_core::v8_static_strings;
use deno_error::JsErrorBox;

#[op2(fast)]
pub fn op_mark_as_untransferable(
  scope: &mut v8::PinScope<'_, '_>,
  ab: v8::Local<v8::ArrayBuffer>,
) {
  v8_static_strings! {
      UNTRANSFERABLE = "untransferable",
  }

  let key = UNTRANSFERABLE.v8_string(scope).unwrap();
  ab.set_detach_key(key.into());
}

#[op2(fast)]
pub fn op_is_ascii(#[buffer] buf: &[u8]) -> bool {
  buf.is_ascii()
}

#[op2(fast)]
pub fn op_is_utf8(#[buffer] buf: &[u8]) -> bool {
  std::str::from_utf8(buf).is_ok()
}

#[op2]
pub fn op_transcode(
  #[buffer] source: &[u8],
  #[string] from_encoding: &str,
  #[string] to_encoding: &str,
) -> Result<Uint8Array, JsErrorBox> {
  match (from_encoding, to_encoding) {
    ("utf8", "ascii") => Ok(utf8_to_ascii(source)),
    ("utf8", "latin1") => Ok(utf8_to_latin1(source)),
    ("utf8", "utf16le") => utf8_to_utf16le(source),
    ("utf16le", "utf8") => utf16le_to_utf8(source),
    ("latin1", "utf16le") | ("ascii", "utf16le") => {
      Ok(latin1_ascii_to_utf16le(source))
    }
    (from, to) => Err(JsErrorBox::generic(format!(
      "Unable to transcode Buffer {from}->{to}"
    ))),
  }
}

fn latin1_ascii_to_utf16le(source: &[u8]) -> Uint8Array {
  let mut result = Vec::with_capacity(source.len() * 2);
  for &byte in source {
    result.push(byte);
    result.push(0);
  }
  result.into()
}

fn utf16le_to_utf8(source: &[u8]) -> Result<Uint8Array, JsErrorBox> {
  let ucs2_vec: Vec<u16> = source
    .chunks_exact(2)
    .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
    .collect();
  String::from_utf16(&ucs2_vec)
    .map(|utf8_string| utf8_string.into_bytes().into())
    .map_err(|e| JsErrorBox::generic(format!("Invalid UTF-16 sequence: {}", e)))
}

fn utf8_to_utf16le(source: &[u8]) -> Result<Uint8Array, JsErrorBox> {
  let utf8_string =
    std::str::from_utf8(source).map_err(JsErrorBox::from_err)?;
  let ucs2_vec: Vec<u16> = utf8_string.encode_utf16().collect();
  let bytes: Vec<u8> = ucs2_vec.iter().flat_map(|&x| x.to_le_bytes()).collect();
  Ok(bytes.into())
}

fn utf8_to_latin1(source: &[u8]) -> Uint8Array {
  let mut latin1_bytes = Vec::with_capacity(source.len());
  let mut i = 0;
  while i < source.len() {
    match source[i] {
      byte if byte <= 0x7F => {
        // ASCII character
        latin1_bytes.push(byte);
        i += 1;
      }
      byte if (0xC2..=0xDF).contains(&byte) && i + 1 < source.len() => {
        // 2-byte UTF-8 sequence
        let codepoint =
          ((byte as u16 & 0x1F) << 6) | (source[i + 1] as u16 & 0x3F);
        latin1_bytes.push(if codepoint <= 0xFF {
          codepoint as u8
        } else {
          b'?'
        });
        i += 2;
      }
      _ => {
        // 3-byte or 4-byte UTF-8 sequence, or invalid UTF-8
        latin1_bytes.push(b'?');
        // Skip to the next valid UTF-8 start byte
        i += 1;
        while i < source.len() && (source[i] & 0xC0) == 0x80 {
          i += 1;
        }
      }
    }
  }
  latin1_bytes.into()
}

fn utf8_to_ascii(source: &[u8]) -> Uint8Array {
  let mut ascii_bytes = Vec::with_capacity(source.len());
  let mut i = 0;
  while i < source.len() {
    match source[i] {
      byte if byte <= 0x7F => {
        // ASCII character
        ascii_bytes.push(byte);
        i += 1;
      }
      _ => {
        // Non-ASCII character
        ascii_bytes.push(b'?');
        // Skip to the next valid UTF-8 start byte
        i += 1;
        while i < source.len() && (source[i] & 0xC0) == 0x80 {
          i += 1;
        }
      }
    }
  }
  ascii_bytes.into()
}

#[op2(fast)]
#[smi]
pub fn op_node_buffer_compare(
  #[buffer] buf1: &[u8],
  #[buffer] buf2: &[u8],
) -> i32 {
  buf1.cmp(buf2) as i32
}

#[op2(fast)]
#[smi]
pub fn op_node_buffer_compare_offset(
  #[buffer] source: &[u8],
  #[buffer] target: &[u8],
  #[smi] source_start: usize,
  #[smi] target_start: usize,
  #[smi] source_end: usize,
  #[smi] target_end: usize,
) -> Result<i32, JsErrorBox> {
  if source_start > source.len() {
    return Err(JsErrorBox::from_err(BufferError::OutOfRangeNamed(
      "sourceStart".to_string(),
    )));
  }
  if target_start > target.len() {
    return Err(JsErrorBox::from_err(BufferError::OutOfRangeNamed(
      "targetStart".to_string(),
    )));
  }

  if source_start > source_end {
    panic!("source_start > source_end");
  }
  if target_start > target_end {
    panic!("target_start > target_end");
  }

  Ok(
    source[source_start..source_end].cmp(&target[target_start..target_end])
      as i32,
  )
}

// Threshold for falling back to V8's internal string copy allocation
// instead of creating an ExternalString to reduce GC finalizer overhead.
const ZERO_COPY_THRESHOLD: usize = 1024;

#[op2(reentrant)]
pub fn op_node_encoding_slice<'a>(
  scope: &mut v8::PinScope<'a, '_>,
  buf: v8::Local<v8::ArrayBufferView>,
  start: v8::Local<v8::Value>,
  end: v8::Local<v8::Value>,
  encoding: u8,
) -> Result<v8::Local<'a, v8::String>, JsErrorBox> {
  let buf_len = buf.byte_length();

  let start =
    parse_array_index(scope, start, 0).map_err(JsErrorBox::from_err)?;
  let mut end =
    parse_array_index(scope, end, buf_len).map_err(JsErrorBox::from_err)?;

  let mut storage = [0; v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP];
  let buf = buf.get_contents(&mut storage);

  if end < start {
    end = start;
  }

  if end > buf.len() {
    return Err(JsErrorBox::from_err(BufferError::OutOfRange));
  }

  if end == start {
    return Ok(v8::String::empty(scope));
  }

  let buffer = &buf[start..end];

  match encoding {
    0 => {
      // utf8Slice
      if buffer.len() <= 256 && buffer.is_ascii() {
        v8::String::new_from_one_byte(scope, buffer, v8::NewStringType::Normal)
      } else {
        // `v8::String::new_from_utf8` does not replace ill-formed UTF-8
        // sequences the same way Node.js does, so decode lossily ourselves.
        // Rust's `from_utf8_lossy` follows the WHATWG "maximal subpart"
        // replacement (one U+FFFD per ill-formed subsequence), matching Node's
        // `Buffer.prototype.toString('utf8')` and `string_decoder`. For valid
        // UTF-8 it borrows the input without allocating.
        let decoded = String::from_utf8_lossy(buffer);
        v8::String::new_from_utf8(
          scope,
          decoded.as_bytes(),
          v8::NewStringType::Normal,
        )
      }
    }
    1 => {
      // latin1Slice
      v8::String::new_from_one_byte(scope, buffer, v8::NewStringType::Normal)
    }
    2 => {
      // asciiSlice
      if buffer.len() > v8::String::MAX_LENGTH {
        // String too long
        None
      } else if buffer.len() > ZERO_COPY_THRESHOLD {
        let ascii_bytes = mask_ascii_fast(buffer);
        // `ascii_bytes` is already a copied clone
        // (not a zero‑copy reference to the ArrayBufferView),
        // so we can zero‑copy create a V8 string from it.
        v8::String::new_external_onebyte(scope, ascii_bytes.into_boxed_slice())
      } else if buffer.is_ascii() {
        // A copy is required to prevent subsequent ArrayBufferView modifications
        // from altering the immutable string.
        // Cannot zero-copy create a V8 string here.
        v8::String::new_from_one_byte(scope, buffer, v8::NewStringType::Normal)
      } else {
        let ascii_bytes = mask_ascii_fast(buffer);
        // Copy bytes to a string
        v8::String::new_from_one_byte(
          scope,
          &ascii_bytes,
          v8::NewStringType::Normal,
        )
      }
    }
    3 => {
      // ucs2Slice
      decode_utf16le_from_bytes(scope, buffer)
    }
    4 => {
      // hexSlice
      if buffer.len() > (v8::String::MAX_LENGTH / 2) {
        // String too long
        None
      } else {
        let target_len = buffer.len() * 2;
        let mut hex_bytes = vec![0u8; target_len];
        // infallible: output is exactly 2x input
        faster_hex::hex_encode(buffer, &mut hex_bytes).unwrap();
        if target_len <= ZERO_COPY_THRESHOLD {
          // Copy bytes to a string
          v8::String::new_from_one_byte(
            scope,
            &hex_bytes,
            v8::NewStringType::Normal,
          )
        } else {
          // Create a V8 string with zero-copy
          v8::String::new_external_onebyte(scope, hex_bytes.into_boxed_slice())
        }
      }
    }
    _ => return Err(JsErrorBox::from_err(BufferError::InvalidType)),
  }
  .ok_or_else(|| JsErrorBox::from_err(BufferError::StringTooLong))
}

#[inline(always)]
fn mask_ascii_fast(bytes: &[u8]) -> Vec<u8> {
  const CHUNK_SIZE: usize = std::mem::size_of::<usize>();
  const MASK: usize = usize::from_ne_bytes([0x7F; CHUNK_SIZE]);

  let len = bytes.len();
  let mut ascii_bytes = Vec::<u8>::with_capacity(len);

  let src = bytes.as_ptr();
  let dst = ascii_bytes.as_mut_ptr();

  // SAFETY:
  // 1. Bounds & Capacity:
  //    - `src` is valid for `len` bytes.
  //    - `dst` has an allocated capacity of `len` bytes.
  //    - If `len >= CHUNK_SIZE`: `i < limit` implies
  //      `i + CHUNK_SIZE < len`. The out-of-loop block at `limit`
  //      accesses exactly the last `CHUNK_SIZE` bytes.
  //    - If `len < CHUNK_SIZE`: The `for` loop bounds are `0..len`.
  //    Therefore, all pointer arithmetic stays within valid bounds.
  // 2. Alignment:
  //    `read_unaligned` and `write_unaligned` are used for `usize`
  //    accesses, preventing UB from potentially unaligned pointers.
  // 3. Initialization:
  //    Every byte from `0` to `len` in `dst` is guaranteed to be
  //    written before `set_len(len)` is called. Overlapping writes
  //    are idempotent and safe.
  unsafe {
    if len >= CHUNK_SIZE {
      let limit = len - CHUNK_SIZE;
      let mut i: usize = 0;
      while i < limit {
        let tmp = src.add(i).cast::<usize>().read_unaligned();
        dst.add(i).cast::<usize>().write_unaligned(tmp & MASK);
        i += CHUNK_SIZE;
      }
      let tmp = src.add(limit).cast::<usize>().read_unaligned();
      dst.add(limit).cast::<usize>().write_unaligned(tmp & MASK);
    } else {
      for i in 0..len {
        dst.add(i).write(src.add(i).read() & 0x7F);
      }
    }

    ascii_bytes.set_len(len);
  }

  ascii_bytes
}

#[inline(always)]
fn decode_utf16le_from_bytes<'a>(
  scope: &mut v8::PinScope<'a, '_>,
  bytes: &[u8],
) -> Option<v8::Local<'a, v8::String>> {
  // UTF-16 must be a multiple of 2 bytes. Discard any trailing odd byte.
  let len = bytes.len() & !1;
  let target_len = len / 2;

  if target_len > v8::String::MAX_LENGTH {
    // String too long
    return None;
  }

  let buf = &bytes[..len];

  #[cfg(target_endian = "little")]
  {
    // Attempt a zero-copy cast to &[u16]
    // SAFETY:
    // `u16` has no invalid bit patterns. Reinterpreting
    // any initialized `u8` pairs as `u16` is safe.
    let (prefix, u16_slice, suffix) = unsafe { buf.align_to::<u16>() };

    if prefix.is_empty() && suffix.is_empty() {
      // Fast path: Memory is perfectly 2-byte aligned.
      // A copy is required to prevent subsequent ArrayBufferView modifications
      // from altering the immutable string.
      // Cannot zero-copy create a V8 string here.
      v8::String::new_from_two_byte(scope, u16_slice, v8::NewStringType::Normal)
    } else {
      // Slow path: Unaligned memory (rare in V8, but must be handled).
      // Use uninitialized memory to avoid Vec's memset(0) overhead.
      let mut u16_data = Vec::<u16>::with_capacity(target_len);

      // SAFETY:
      // 1. `buf` is valid for reads of `len` bytes.
      // 2. `u16_data` has a capacity of `target_len`
      //    `u16`s (exactly `len` bytes), so writing
      //    `len` bytes is within bounds.
      // 3. Source and destination do not overlap.
      // 4. `copy_nonoverlapping` fully initializes
      //    the memory, making `set_len` safe.
      unsafe {
        // Memcpy the data byte-by-byte into the newly allocated Vec memory.
        std::ptr::copy_nonoverlapping(
          buf.as_ptr(),
          u16_data.as_mut_ptr().cast::<u8>(),
          len,
        );
        // Manually set the length.
        u16_data.set_len(target_len);
      }

      // `u16_data` is already a copied clone
      // (not a zero‑copy reference to the ArrayBufferView),
      // so we can zero‑copy create a V8 string from it.
      if len <= ZERO_COPY_THRESHOLD {
        // Copy bytes to a string
        v8::String::new_from_two_byte(
          scope,
          &u16_data,
          v8::NewStringType::Normal,
        )
      } else {
        // Create a V8 string with zero-copy
        v8::String::new_external_twobyte(scope, u16_data.into_boxed_slice())
      }
    }
  }

  // Fallback for big-endian architectures (uncommon environments).
  #[cfg(target_endian = "big")]
  {
    let u16_data = buf
      .chunks_exact(2)
      .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
      .collect();

    // `u16_data` is already a copied clone
    // (not a zero‑copy reference to the ArrayBufferView),
    // so we can zero‑copy create a V8 string from it.
    if len <= ZERO_COPY_THRESHOLD {
      // Copy bytes to a string
      v8::String::new_from_two_byte(scope, &u16_data, v8::NewStringType::Normal)
    } else {
      // Create a V8 string with zero-copy
      v8::String::new_external_twobyte(scope, u16_data.into_boxed_slice())
    }
  }
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
enum BufferError {
  #[error(
    "Cannot create a string longer than 0x{:x} characters",
    v8::String::MAX_LENGTH
  )]
  #[class(generic)]
  #[property("code" = "ERR_STRING_TOO_LONG")]
  StringTooLong,
  #[error("Invalid type")]
  #[class(generic)]
  InvalidType,
  #[error("Index out of range")]
  #[class(range)]
  #[property("code" = "ERR_OUT_OF_RANGE")]
  OutOfRange,
  #[error("The value of \"{0}\" is out of range.")]
  #[class(range)]
  #[property("code" = "ERR_OUT_OF_RANGE")]
  OutOfRangeNamed(String),
}

#[inline(always)]
fn parse_array_index(
  scope: &mut v8::PinScope<'_, '_>,
  arg: v8::Local<v8::Value>,
  default: usize,
) -> Result<usize, BufferError> {
  if arg.is_undefined() {
    return Ok(default);
  }

  let Some(arg) = arg.integer_value(scope) else {
    return Err(BufferError::InvalidType);
  };
  if arg < 0 {
    return Err(BufferError::OutOfRange);
  }
  if arg > isize::MAX as i64 {
    return Err(BufferError::OutOfRange);
  }
  Ok(arg as usize)
}