Skip to main content

atmos/os_lib/ecma/builtins/
encoding.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5// ===== base64(btoa / atob)。バイト列は latin1/ASCII 前提(多バイトは非対応)=====
6pub(crate) const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7/// バイト列を base64 文字列へエンコードする共通処理(`btoa`/`Uint8Array.prototype.toBase64` で共有)。
8pub(crate) fn bytes_to_base64(bytes: &[u8]) -> String {
9    let mut out = String::new();
10    for chunk in bytes.chunks(3) {
11        let b0 = chunk.first().copied().unwrap_or(0);
12        let b1 = chunk.get(1).copied().unwrap_or(0);
13        let b2 = chunk.get(2).copied().unwrap_or(0);
14        out.push(B64_CHARS[(b0 >> 2) as usize] as char);
15        out.push(B64_CHARS[(((b0 & 0x3) << 4) | (b1 >> 4)) as usize] as char);
16        out.push(if chunk.len() > 1 {
17            B64_CHARS[(((b1 & 0xf) << 2) | (b2 >> 6)) as usize] as char
18        } else {
19            '='
20        });
21        out.push(if chunk.len() > 2 {
22            B64_CHARS[(b2 & 0x3f) as usize] as char
23        } else {
24            '='
25        });
26    }
27    out
28}
29
30/// base64 文字列をバイト列へデコードする共通処理(`atob`/`Uint8Array.fromBase64` で共有)。
31/// 未知の文字(改行等)は無視する簡略実装。
32pub(crate) fn base64_to_bytes(s: &str) -> Vec<u8> {
33    let mut bits: u32 = 0;
34    let mut nbits = 0u32;
35    let mut out: Vec<u8> = Vec::new();
36    for c in s.bytes() {
37        let v = match c {
38            b'A'..=b'Z' => c - b'A',
39            b'a'..=b'z' => c - b'a' + 26,
40            b'0'..=b'9' => c - b'0' + 52,
41            b'+' | b'-' => 62, // '-' は base64url 版のエイリアスとして許容
42            b'/' | b'_' => 63, // '_' は base64url 版のエイリアスとして許容
43            _ => continue,
44        };
45        bits = (bits << 6) | v as u32;
46        nbits += 6;
47        if nbits >= 8 {
48            nbits -= 8;
49            out.push((bits >> nbits) as u8);
50        }
51    }
52    out
53}
54
55/// バイト列を小文字16進文字列へエンコードする(`Uint8Array.prototype.toHex`)。
56pub(crate) fn bytes_to_hex(bytes: &[u8]) -> String {
57    const HEX: &[u8; 16] = b"0123456789abcdef";
58    let mut out = String::with_capacity(bytes.len() * 2);
59    for &b in bytes {
60        out.push(HEX[(b >> 4) as usize] as char);
61        out.push(HEX[(b & 0xf) as usize] as char);
62    }
63    out
64}
65
66/// 16進文字列をバイト列へデコードする(`Uint8Array.fromHex`)。奇数長や不正文字は `None`。
67pub(crate) fn hex_to_bytes(s: &str) -> Option<Vec<u8>> {
68    let s = s.as_bytes();
69    if !s.len().is_multiple_of(2) {
70        return None;
71    }
72    fn nibble(c: u8) -> Option<u8> {
73        match c {
74            b'0'..=b'9' => Some(c - b'0'),
75            b'a'..=b'f' => Some(c - b'a' + 10),
76            b'A'..=b'F' => Some(c - b'A' + 10),
77            _ => None,
78        }
79    }
80    let mut out = Vec::with_capacity(s.len() / 2);
81    for pair in s.chunks(2) {
82        let hi = nibble(pair[0])?;
83        let lo = nibble(pair[1])?;
84        out.push((hi << 4) | lo);
85    }
86    Some(out)
87}
88
89/// WHATWG の forgiving-base64 decode(`atob`)。空白を除き、末尾の `=` を外し、長さ・文字が不正なら `None`。
90pub(crate) fn forgiving_base64_decode(s: &str) -> Option<Vec<u8>> {
91    let mut data: Vec<u8> = Vec::with_capacity(s.len());
92    for c in s.chars() {
93        match c {
94            '\t' | '\n' | '\x0c' | '\r' | ' ' => {}
95            c if c.is_ascii() => data.push(c as u8),
96            _ => return None,
97        }
98    }
99    if data.len().is_multiple_of(4) {
100        if data.ends_with(b"==") {
101            data.truncate(data.len() - 2);
102        } else if data.ends_with(b"=") {
103            data.truncate(data.len() - 1);
104        }
105    }
106    if data.len() % 4 == 1 {
107        return None;
108    }
109    let mut bits: u32 = 0;
110    let mut nbits = 0u32;
111    let mut out: Vec<u8> = Vec::with_capacity(data.len() * 3 / 4);
112    for c in data {
113        let v = match c {
114            b'A'..=b'Z' => c - b'A',
115            b'a'..=b'z' => c - b'a' + 26,
116            b'0'..=b'9' => c - b'0' + 52,
117            b'+' => 62,
118            b'/' => 63,
119            _ => return None,
120        };
121        bits = (bits << 6) | v as u32;
122        nbits += 6;
123        if nbits >= 8 {
124            nbits -= 8;
125            out.push((bits >> nbits) as u8);
126        }
127    }
128    Some(out)
129}
130
131/// TypedArray インスタンスの要素を u8 バイト列として取り出す(Uint8Array 専用機能で使用)。
132pub(crate) fn ta_to_bytes(this: &Value) -> Vec<u8> {
133    if let Value::Object(o) = this {
134        if let ObjKind::Bytes(st) = &o.borrow().kind {
135            return st.to_vec();
136        }
137        if let ObjKind::Array(items) = &o.borrow().kind {
138            return items.iter().map(|v| v.to_number() as i64 as u8).collect();
139        }
140    }
141    Vec::new()
142}
143
144/// `Uint8Array.prototype.toBase64()`(ES2024/2025)。
145pub(crate) fn ta_to_base64(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
146    Ok(Value::str(bytes_to_base64(&ta_to_bytes(&this))))
147}
148
149/// `Uint8Array.prototype.toHex()`(ES2024/2025)。
150pub(crate) fn ta_to_hex(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
151    Ok(Value::str(bytes_to_hex(&ta_to_bytes(&this))))
152}
153
154/// `Uint8Array.fromBase64(str)`(ES2024/2025 静的メソッド)。
155pub(crate) fn ta_from_base64(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
156    let s = it.to_string_value(arg(a, 0))?;
157    Ok(make_uint8array(it, base64_to_bytes(&s)))
158}
159
160/// `Uint8Array.fromHex(str)`(ES2024/2025 静的メソッド)。不正な16進文字列は例外を投げる。
161pub(crate) fn ta_from_hex(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
162    let s = it.to_string_value(arg(a, 0))?;
163    match hex_to_bytes(&s) {
164        Some(bytes) => Ok(make_uint8array(it, bytes)),
165        None => {
166            let err = syntax_error_ctor(
167                it,
168                Value::Undefined,
169                &[Value::str("Uint8Array.fromHex: invalid hex string")],
170            )?;
171            Err(err)
172        }
173    }
174}
175
176/// デコードしたバイト列を既存の `this`(Uint8Array)の先頭から上書きし、
177/// `{ read, written }`(`read` は入力文字列の消費文字数、`written` は書き込んだ
178/// バイト数)を返す共通処理。`setFromBase64`/`setFromHex` で共有する。
179/// `toBase64`/`toHex`(読み取り)と `fromBase64`/`fromHex`(新規生成)は
180/// 実装済みだったが、既存バッファへインプレースで書き込む対になる
181/// `setFromBase64`/`setFromHex`(ES2024/2025)が丸ごと未対応だった。
182pub(crate) fn ta_write_bytes_into(this: &Value, bytes: &[u8], consumed_len: usize) -> Value {
183    let mut written = 0usize;
184    if let Value::Object(o) = this {
185        if let ObjKind::Bytes(st) = &o.borrow().kind {
186            written = bytes.len().min(st.len);
187            for (i, byte) in bytes.iter().take(written).enumerate() {
188                st.set(i, *byte as f64);
189            }
190        }
191        let mut b = o.borrow_mut();
192        if let ObjKind::Array(items) = &mut b.kind {
193            let cap = items.len();
194            written = bytes.len().min(cap);
195            for (slot, byte) in items.iter_mut().zip(bytes.iter()).take(written) {
196                *slot = Value::Number(*byte as f64);
197            }
198        }
199    }
200    let read = if written < bytes.len() {
201        // 途中で容量切れになった場合、書き込めた分に対応する入力文字数のみ「読んだ」扱いにする。
202        consumed_len * written / bytes.len().max(1)
203    } else {
204        consumed_len
205    };
206    let o = Obj::plain();
207    {
208        let mut ob = o.borrow_mut();
209        ob.props.insert("read".into(), Value::Number(read as f64));
210        ob.props.insert("written".into(), Value::Number(written as f64));
211    }
212    Value::Object(o)
213}
214
215fn decode_base64_char(b: u8, url_safe: bool) -> Option<u8> {
216    match b {
217        b'A'..=b'Z' => Some(b - b'A'),
218        b'a'..=b'z' => Some(b - b'a' + 26),
219        b'0'..=b'9' => Some(b - b'0' + 52),
220        b'+' if !url_safe => Some(62),
221        b'/' if !url_safe => Some(63),
222        b'-' if url_safe => Some(62),
223        b'_' if url_safe => Some(63),
224        _ => None,
225    }
226}
227
228fn is_ascii_ws(b: u8) -> bool {
229    matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')
230}
231
232#[derive(Clone, Copy, PartialEq, Eq)]
233enum LastChunkHandling {
234    Loose,
235    Strict,
236    StopBeforePartial,
237}
238
239fn parse_base64_options(it: &mut Interp, opts: &Value) -> Result<(bool, LastChunkHandling), Value> {
240    if matches!(opts, Value::Undefined) {
241        return Ok((false, LastChunkHandling::Loose));
242    }
243    if !matches!(opts, Value::Object(_)) {
244        return Err(it.type_error("Base64 options must be an object"));
245    }
246    let alph = it.get_property(opts, "alphabet")?;
247    let url_safe = match &alph {
248        Value::Undefined => false,
249        Value::Str(s) if s.as_str() == "base64" => false,
250        Value::Str(s) if s.as_str() == "base64url" => true,
251        _ => return Err(it.type_error("Invalid base64 alphabet option")),
252    };
253    let lch = it.get_property(opts, "lastChunkHandling")?;
254    let handling = match &lch {
255        Value::Undefined => LastChunkHandling::Loose,
256        Value::Str(s) if s.as_str() == "loose" => LastChunkHandling::Loose,
257        Value::Str(s) if s.as_str() == "strict" => LastChunkHandling::Strict,
258        Value::Str(s) if s.as_str() == "stop-before-partial" => LastChunkHandling::StopBeforePartial,
259        _ => return Err(it.type_error("Invalid lastChunkHandling option")),
260    };
261    Ok((url_safe, handling))
262}
263
264type Base64DecodeResult = Result<(Vec<u8>, usize), (&'static str, Vec<u8>)>;
265
266fn decode_base64_into(
267    s: &str,
268    url_safe: bool,
269    handling: LastChunkHandling,
270    max_bytes: usize,
271) -> Base64DecodeResult {
272    let bytes = s.as_bytes();
273    let mut out = Vec::new();
274    if max_bytes == 0 {
275        return Ok((out, 0));
276    }
277    let mut read = 0usize;
278    let mut idx = 0usize;
279    let mut chunk: [u8; 4] = [0; 4];
280    let mut chunk_pos: [usize; 4] = [0; 4];
281    let mut chunk_len = 0usize;
282    let mut pad_count = 0usize;
283    let mut saw_pad = false;
284
285    while idx < bytes.len() {
286        let b = bytes[idx];
287        if is_ascii_ws(b) {
288            idx += 1;
289            continue;
290        }
291        if b == b'=' {
292            if chunk_len < 2 || saw_pad && pad_count >= 2 {
293                return Err(("Unexpected padding in base64 string", out));
294            }
295            saw_pad = true;
296            pad_count += 1;
297            chunk[chunk_len] = 0;
298            chunk_pos[chunk_len] = idx + 1;
299            chunk_len += 1;
300            idx += 1;
301        } else if saw_pad {
302            return Err(("Unexpected character after base64 padding", out));
303        } else if let Some(val) = decode_base64_char(b, url_safe) {
304            chunk[chunk_len] = val;
305            chunk_pos[chunk_len] = idx + 1;
306            chunk_len += 1;
307            idx += 1;
308        } else {
309            return Err(("Invalid character in base64 string", out));
310        }
311
312        if chunk_len == 4 {
313            let emit_len = match pad_count {
314                0 => 3,
315                1 => 2,
316                2 => 1,
317                _ => return Err(("Invalid base64 padding", out)),
318            };
319            if handling == LastChunkHandling::Strict {
320                if pad_count == 1 && (chunk[2] & 0x03) != 0 {
321                    return Err(("Non-zero padding bits in strict mode", out));
322                }
323                if pad_count == 2 && (chunk[1] & 0x0f) != 0 {
324                    return Err(("Non-zero padding bits in strict mode", out));
325                }
326            }
327            if saw_pad {
328                while idx < bytes.len() && is_ascii_ws(bytes[idx]) {
329                    idx += 1;
330                }
331                if idx < bytes.len() {
332                    return Err(("Trailing characters after base64 padding", out));
333                }
334            }
335            if out.len() + emit_len > max_bytes {
336                return Ok((out, read));
337            }
338            let combined = ((chunk[0] as u32) << 18)
339                | ((chunk[1] as u32) << 12)
340                | ((chunk[2] as u32) << 6)
341                | (chunk[3] as u32);
342            out.push(((combined >> 16) & 0xff) as u8);
343            if emit_len >= 2 {
344                out.push(((combined >> 8) & 0xff) as u8);
345            }
346            if emit_len >= 3 {
347                out.push((combined & 0xff) as u8);
348            }
349            read = chunk_pos[3];
350            if saw_pad {
351                return Ok((out, bytes.len()));
352            }
353            if out.len() == max_bytes {
354                return Ok((out, read));
355            }
356            chunk_len = 0;
357            pad_count = 0;
358        }
359    }
360
361    if chunk_len == 0 {
362        return Ok((out, bytes.len()));
363    }
364    if saw_pad {
365        if handling == LastChunkHandling::StopBeforePartial {
366            return Ok((out, read));
367        }
368        return Err(("Incomplete padded base64 chunk", out));
369    }
370    match handling {
371        LastChunkHandling::StopBeforePartial => Ok((out, read)),
372        LastChunkHandling::Strict => Err(("Incomplete base64 chunk in strict mode", out)),
373        LastChunkHandling::Loose => {
374            if chunk_len == 1 {
375                return Err(("Single trailing base64 character", out));
376            }
377            let emit_len = if chunk_len == 2 { 1 } else { 2 };
378            if out.len() + emit_len > max_bytes {
379                return Ok((out, read));
380            }
381            let combined = ((chunk[0] as u32) << 18)
382                | ((chunk[1] as u32) << 12)
383                | ((chunk[2] as u32) << 6);
384            out.push(((combined >> 16) & 0xff) as u8);
385            if emit_len >= 2 {
386                out.push(((combined >> 8) & 0xff) as u8);
387            }
388            Ok((out, bytes.len()))
389        }
390    }
391}
392
393/// `Uint8Array.prototype.setFromBase64(str [, options])`(ES2024/2025)。
394pub(crate) fn ta_set_from_base64(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
395    let max_bytes = if let Value::Object(o) = &this {
396        let b = o.borrow();
397        if crate::os_lib::ecma::value::ta_is_immutable(&b) {
398            return Err(it.type_error("Uint8Array buffer is immutable"));
399        }
400        if let Some(len) = crate::os_lib::ecma::value::ta_effective_len(&b) {
401            len
402        } else {
403            return Err(it.type_error("Uint8Array buffer is detached or out of bounds"));
404        }
405    } else {
406        0
407    };
408    let s_val = arg(a, 0);
409    let Value::Str(s) = &s_val else {
410        return Err(it.type_error("Uint8Array.prototype.setFromBase64 requires a string argument"));
411    };
412    if is_symbol_like_key(s) {
413        return Err(it.type_error("Uint8Array.prototype.setFromBase64 requires a string argument"));
414    }
415    let (url_safe, handling) = parse_base64_options(it, &arg(a, 1))?;
416    match decode_base64_into(s, url_safe, handling, max_bytes) {
417        Ok((bytes, read)) => {
418            let written = bytes.len();
419            if let Value::Object(o) = &this {
420                if let ObjKind::Bytes(st) = &o.borrow().kind {
421                    for (i, byte) in bytes.iter().enumerate() {
422                        st.set(i, *byte as f64);
423                    }
424                }
425            }
426            let o = Obj::plain();
427            {
428                let mut ob = o.borrow_mut();
429                ob.props.insert("read".into(), Value::Number(read as f64));
430                ob.props.insert("written".into(), Value::Number(written as f64));
431            }
432            Ok(Value::Object(o))
433        }
434        Err((msg, bytes)) => {
435            if let Value::Object(o) = &this {
436                if let ObjKind::Bytes(st) = &o.borrow().kind {
437                    for (i, byte) in bytes.iter().enumerate() {
438                        st.set(i, *byte as f64);
439                    }
440                }
441            }
442            let err = syntax_error_ctor(it, Value::Undefined, &[Value::str(msg)])?;
443            Err(err)
444        }
445    }
446}
447
448/// `Uint8Array.prototype.setFromHex(str)`(ES2024/2025)。不正な16進文字列は例外を投げる。
449pub(crate) fn ta_set_from_hex(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
450    if let Value::Object(o) = &this {
451        let b = o.borrow();
452        if crate::os_lib::ecma::value::ta_is_immutable(&b) {
453            return Err(it.type_error("Uint8Array buffer is immutable"));
454        }
455        if crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) {
456            return Err(it.type_error("Uint8Array buffer is detached or out of bounds"));
457        }
458    }
459    let s = it.to_string_value(arg(a, 0))?;
460    match hex_to_bytes(&s) {
461        Some(bytes) => {
462            let len = s.chars().count();
463            Ok(ta_write_bytes_into(&this, &bytes, len))
464        }
465        None => {
466            let err = syntax_error_ctor(
467                it,
468                Value::Undefined,
469                &[Value::str("Uint8Array.setFromHex: invalid hex string")],
470            )?;
471            Err(err)
472        }
473    }
474}
475
476// ===== URI エンコード(encodeURIComponent/decodeURIComponent/encodeURI/decodeURI)=====
477// URLSearchParams の form-urlencoded(+ = 空白)とは別の RFC3986 %XX 方式。
478
479/// `%XX` を1バイトへ復元する共通デコーダ。`plus_as_space` が true の場合のみ
480/// `+` を空白として扱う(form-urlencoded 用。encodeURIComponent 系では false)。
481pub(crate) fn percent_decode(s: &str, plus_as_space: bool) -> String {
482    let bytes = s.as_bytes();
483    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
484    let mut i = 0;
485    while i < bytes.len() {
486        if bytes[i] == b'%' && i + 2 < bytes.len() {
487            let h1 = bytes[i + 1];
488            let h2 = bytes[i + 2];
489            if let (Some(n1), Some(n2)) = (char::from(h1).to_digit(16), char::from(h2).to_digit(16)) {
490                let byte = ((n1 << 4) | n2) as u8;
491                out.push(byte);
492                i += 3;
493                continue;
494            }
495        }
496        if plus_as_space && bytes[i] == b'+' {
497            out.push(b' ');
498        } else {
499            out.push(bytes[i]);
500        }
501        i += 1;
502    }
503    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
504}
505
506/// `encodeURIComponent` 相当。未エスケープ文字は RFC3986 unreserved + `!'()*`。
507pub(crate) fn percent_encode_component(s: &str) -> String {
508    let mut out = String::new();
509    for b in s.as_bytes() {
510        match *b {
511            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*'
512            | b'\'' | b'(' | b')' => {
513                out.push(*b as char);
514            }
515            _ => out.push_str(&alloc::format!("%{:02X}", b)),
516        }
517    }
518    out
519}
520
521/// `encodeURI` 相当。encodeURIComponent の非エスケープ集合に加え、URI 予約文字
522/// (`;/?:@&=+$,#`) も未エスケープのまま残す(コンポーネントではなくURI全体用のため)。
523pub(crate) fn percent_encode_uri(s: &str) -> String {
524    let mut out = String::new();
525    for b in s.as_bytes() {
526        match *b {
527            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*'
528            | b'\'' | b'(' | b')' | b';' | b'/' | b'?' | b':' | b'@' | b'&' | b'=' | b'+'
529            | b'$' | b',' | b'#' => {
530                out.push(*b as char);
531            }
532            _ => out.push_str(&alloc::format!("%{:02X}", b)),
533        }
534    }
535    out
536}
537
538pub(crate) fn js_encode_uri_component(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
539    Ok(Value::str(percent_encode_component(&it.to_string_value(arg(a, 0))?)))
540}
541pub(crate) fn js_decode_uri_component(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
542    match uri_decode(&it.to_string_value(arg(a, 0))?, "") {
543        Some(s) => Ok(Value::str(s)),
544        None => Err(it.error_of_kind("URIError", "URI malformed")),
545    }
546}
547pub(crate) fn js_encode_uri(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
548    Ok(Value::str(percent_encode_uri(&it.to_string_value(arg(a, 0))?)))
549}
550pub(crate) fn js_decode_uri(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
551    match uri_decode(&it.to_string_value(arg(a, 0))?, ";/?:@&=+$,#") {
552        Some(s) => Ok(Value::str(s)),
553        None => Err(it.error_of_kind("URIError", "URI malformed")),
554    }
555}
556
557/// 仕様の Decode(ECMA-262 19.2.6.1.2)。`%XX` が壊れている・UTF-8 として読めないなら None(URIError)。
558/// `reserved` の文字(`decodeURI` の `;/?:@&=+$,#`)に当たる `%XX` は元のまま残す。
559/// 【2026-11-16】以前は `percent_decode` の寛容な版を使い、`decodeURIComponent("%")` が例外にならず、
560/// `decodeURI("%2f")` が `/` になっていた。
561fn uri_decode(s: &str, reserved: &str) -> Option<String> {
562    let bytes = s.as_bytes();
563    let hex = |i: usize| -> Option<u8> {
564        let h1 = char::from(*bytes.get(i + 1)?).to_digit(16)?;
565        let h2 = char::from(*bytes.get(i + 2)?).to_digit(16)?;
566        (*bytes.get(i)? == b'%').then_some(((h1 << 4) | h2) as u8)
567    };
568    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
569    let mut i = 0;
570    while i < bytes.len() {
571        if bytes[i] != b'%' {
572            out.push(bytes[i]);
573            i += 1;
574            continue;
575        }
576        let b = hex(i)?;
577        if b < 0x80 {
578            if reserved.as_bytes().contains(&b) {
579                out.extend_from_slice(bytes.get(i..i + 3)?);
580            } else {
581                out.push(b);
582            }
583            i += 3;
584            continue;
585        }
586        let n = match b {
587            0xC0..=0xDF => 2,
588            0xE0..=0xEF => 3,
589            0xF0..=0xF7 => 4,
590            _ => return None,
591        };
592        let mut seq = alloc::vec![b];
593        for k in 1..n {
594            let c = hex(i + 3 * k)?;
595            if c & 0xC0 != 0x80 {
596                return None;
597            }
598            seq.push(c);
599        }
600        core::str::from_utf8(&seq).ok()?;
601        out.extend_from_slice(&seq);
602        i += 3 * n;
603    }
604    String::from_utf8(out).ok()
605}
606
607/// `escape(str)`(Annex B.2.1.1。ES6 で非推奨だが `encodeURI` 系登場以前からの
608/// 遺産として実務コードになお残る)が丸ごと未対応だった。仕様は UTF-16
609/// コード単位ベースだが、この処理系の文字列は UTF-8(Rust `String`)のため
610/// Unicode スカラー値(`char`)単位で近似する(BMP 外文字のサロゲートペア
611/// 分割は考慮しない、他の Unicode 境界処理と同水準の簡略化)。
612pub(crate) fn js_escape(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
613    let s = it.to_string_value(arg(a, 0))?;
614    let mut out = String::new();
615    for c in s.chars() {
616        let unreserved =
617            matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '@' | '*' | '_' | '+' | '-' | '.' | '/');
618        if unreserved {
619            out.push(c);
620        } else {
621            let cp = c as u32;
622            if cp <= 0xFF {
623                out.push_str(&alloc::format!("%{:02X}", cp));
624            } else {
625                out.push_str(&alloc::format!("%u{:04X}", cp));
626            }
627        }
628    }
629    Ok(Value::str(out))
630}
631/// `unescape(str)`(Annex B.2.1.2)。`escape` の逆変換。`%XX`/`%uXXXX` を復元し、
632/// どちらの形にも一致しない `%` はそのまま素通しする(仕様どおり)。
633pub(crate) fn js_unescape(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
634    let s = it.to_string_value(arg(a, 0))?;
635    let chars: Vec<char> = s.chars().collect();
636    let mut out = String::new();
637    let mut i = 0;
638    while i < chars.len() {
639        if chars[i] == '%' && i + 6 <= chars.len() && chars[i + 1] == 'u' {
640            let hex: String = chars[i + 2..i + 6].iter().collect();
641            if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
642                out.push(ch);
643                i += 6;
644                continue;
645            }
646        }
647        if chars[i] == '%' && i + 3 <= chars.len() {
648            let hex: String = chars[i + 1..i + 3].iter().collect();
649            if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
650                out.push(ch);
651                i += 3;
652                continue;
653            }
654        }
655        out.push(chars[i]);
656        i += 1;
657    }
658    Ok(Value::str(out))
659}
660
661// ===== 乱数(crypto / randomUUID 用、Math.random と同じ xorshift64*)=====
662pub(crate) fn next_rand_u64() -> u64 {
663    let mut x = RNG_SEED.load(Ordering::Relaxed);
664    if x == RNG_SEED_UNSET {
665        x = boot_seed();
666    }
667    x ^= x >> 12;
668    x ^= x << 25;
669    x ^= x >> 27;
670    RNG_SEED.store(x, Ordering::Relaxed);
671    x.wrapping_mul(0x2545F4914F6CDD1D)
672}
673
674/// 乱数の種(起動ごとに変える)。現在時刻(秒)と起動からの経過(マイクロ秒)を混ぜる。
675///
676/// 【2026-11-12】以前は種が固定の定数で、`Math.random`・`crypto.getRandomValues`・`crypto.randomUUID` が
677/// 起動のたびに同じ列を返していた(YouTube の再生の識別子・訪問者の識別子が毎回同じになる)。
678/// 暗号用の乱数源ではない(予測できる)。TLS の鍵には使っていない。
679fn boot_seed() -> u64 {
680    let unix = crate::os_lib::platform::unix_time().unwrap_or(0);
681    let us = crate::os_lib::platform::now_us();
682    // splitmix64 で混ぜる。0 と未設定の印は避ける(xorshift は 0 から動かない)。
683    let mut z = unix.wrapping_mul(0x9E3779B97F4A7C15) ^ us.rotate_left(32) ^ 0xD1B54A32D192ED03;
684    z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
685    z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
686    z ^= z >> 31;
687    if z == 0 || z == RNG_SEED_UNSET {
688        z = 0x9E3779B97F4A7C15;
689    }
690    z
691}
692