Skip to main content

atmos/os_lib/ecma/
bigint.rs

1//! 任意精度整数 BigInt の実装。
2//!
3//! ECMAScript の BigInt セマンティクスに沿った符号付き多倍長整数。
4//! 内部表現は「符号 + ベース 2^32 のリム列(リトルエンディアン: limbs[0] が最下位)」。
5//! ゼロは `negative=false` かつ `limbs` 空(正規形)で表す。
6//! no_std 環境のため alloc のみ使用し、除算は素朴な long division を用いる。
7
8use alloc::string::String;
9use alloc::vec::Vec;
10use core::cmp::Ordering;
11
12/// ベース 2^32 のリムで表す符号付き任意精度整数。
13#[derive(Clone, PartialEq, Eq)]
14pub struct BigInt {
15    /// true なら負。ゼロのときは必ず false(正規形)。
16    negative: bool,
17    /// 絶対値のリム列(リトルエンディアン)。末尾の 0 は持たない(正規形)。
18    limbs: Vec<u32>,
19}
20
21impl BigInt {
22    /// 値 0。
23    pub fn zero() -> Self {
24        BigInt {
25            negative: false,
26            limbs: Vec::new(),
27        }
28    }
29
30    /// ゼロかどうか。
31    pub fn is_zero(&self) -> bool {
32        self.limbs.is_empty()
33    }
34
35    /// 末尾の 0 リムを除去し、ゼロなら符号を正に揃える(正規形化)。
36    fn normalize(mut self) -> Self {
37        while let Some(&last) = self.limbs.last() {
38            if last == 0 {
39                self.limbs.pop();
40            } else {
41                break;
42            }
43        }
44        if self.limbs.is_empty() {
45            self.negative = false;
46        }
47        self
48    }
49
50    /// i64 から生成。
51    pub fn from_i64(mut v: i64) -> Self {
52        if v == 0 {
53            return BigInt::zero();
54        }
55        let negative = v < 0;
56        // i64::MIN の絶対値はオーバーフローするため u64 で扱う。
57        let mut mag = if negative {
58            (v as i128).unsigned_abs()
59        } else {
60            v as u128
61        };
62        let _ = &mut v;
63        let mut limbs = Vec::new();
64        while mag > 0 {
65            limbs.push((mag & 0xFFFF_FFFF) as u32);
66            mag >>= 32;
67        }
68        BigInt { negative, limbs }.normalize()
69    }
70
71    /// u64 から生成(常に非負)。`DataView.prototype.getBigUint64` 用。
72    pub fn from_u64(v: u64) -> Self {
73        if v == 0 {
74            return BigInt::zero();
75        }
76        let mut mag = v;
77        let mut limbs = Vec::new();
78        while mag > 0 {
79            limbs.push((mag & 0xFFFF_FFFF) as u32);
80            mag >>= 32;
81        }
82        BigInt { negative: false, limbs }.normalize()
83    }
84
85    /// f64 から生成(整数値のみ受理。小数・非有限は None)。
86    pub fn from_f64(v: f64) -> Option<Self> {
87        if !v.is_finite() {
88            return None;
89        }
90        if libm::trunc(v) != v {
91            return None;
92        }
93        if v == 0.0 {
94            return Some(BigInt::zero());
95        }
96        let negative = v < 0.0;
97        let mut mag = libm::fabs(v);
98        // 2^32 進で下位から取り出す。f64 は 2^53 まで整数を正確に表現できるが、
99        // それを超える大きさも近似的に分解する(仕様の厳密さより実用性を優先)。
100        let mut limbs = Vec::new();
101        let base = 4294967296.0_f64; // 2^32
102        while mag >= 1.0 {
103            let rem = mag - libm::floor(mag / base) * base;
104            limbs.push(rem as u32);
105            mag = libm::floor(mag / base);
106        }
107        Some(BigInt { negative, limbs }.normalize())
108    }
109
110    /// 十進文字列をパース(先頭に符号可、`_` 区切り許容)。失敗で None。
111    pub fn parse_decimal(s: &str) -> Option<Self> {
112        let t = s.trim();
113        if t.is_empty() {
114            return Some(BigInt::zero());
115        }
116        let (negative, digits) = match t.strip_prefix('-') {
117            Some(rest) => (true, rest),
118            None => (false, t.strip_prefix('+').unwrap_or(t)),
119        };
120        if digits.is_empty() {
121            return None;
122        }
123        let mut acc = BigInt::zero();
124        let ten = BigInt::from_i64(10);
125        for ch in digits.chars() {
126            if ch == '_' {
127                continue;
128            }
129            let d = ch.to_digit(10)?;
130            acc = acc.mul(&ten).add(&BigInt::from_i64(d as i64));
131        }
132        acc.negative = negative;
133        Some(acc.normalize())
134    }
135
136    /// ECMAScript `StringToBigInt` 仕様準拠の厳格パーサ(`_` 禁止、非十進への符号禁止)。
137    pub fn parse_js_string(s: &str) -> Option<Self> {
138        let t = s.trim_matches(|c: char| {
139            c.is_ascii_whitespace()
140                || matches!(
141                    c,
142                    '\u{000B}'
143                        | '\u{000C}'
144                        | '\u{00A0}'
145                        | '\u{1680}'
146                        | '\u{2000}'..='\u{200A}'
147                        | '\u{2028}'
148                        | '\u{2029}'
149                        | '\u{202F}'
150                        | '\u{205F}'
151                        | '\u{3000}'
152                        | '\u{FEFF}'
153                )
154        });
155        if t.is_empty() {
156            return Some(BigInt::zero());
157        }
158        if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
159            return Self::parse_radix_strict(h, 16);
160        }
161        if let Some(o) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
162            return Self::parse_radix_strict(o, 8);
163        }
164        if let Some(b) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
165            return Self::parse_radix_strict(b, 2);
166        }
167        let (neg, digits) = match t.strip_prefix('-') {
168            Some(r) => (true, r),
169            None => (false, t.strip_prefix('+').unwrap_or(t)),
170        };
171        Self::parse_radix_strict(digits, 10).map(|mut v| {
172            if neg {
173                v.negative = !v.negative;
174            }
175            v.normalize()
176        })
177    }
178
179    fn parse_radix_strict(digits: &str, radix: u32) -> Option<Self> {
180        if digits.is_empty() {
181            return None;
182        }
183        let mut acc = BigInt::zero();
184        let base = BigInt::from_i64(radix as i64);
185        for ch in digits.chars() {
186            let d = ch.to_digit(radix)?;
187            acc = acc.mul(&base).add(&BigInt::from_i64(d as i64));
188        }
189        Some(acc)
190    }
191
192    /// 文字列をパース(0x/0o/0b 接頭辞対応、それ以外は十進)。
193    pub fn parse_str(s: &str) -> Option<Self> {
194        let t = s.trim();
195        let (neg, body) = match t.strip_prefix('-') {
196            Some(r) => (true, r),
197            None => (false, t.strip_prefix('+').unwrap_or(t)),
198        };
199        let parsed = if let Some(h) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
200            Self::parse_radix(h, 16)
201        } else if let Some(o) = body.strip_prefix("0o").or_else(|| body.strip_prefix("0O")) {
202            Self::parse_radix(o, 8)
203        } else if let Some(b) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
204            Self::parse_radix(b, 2)
205        } else {
206            Self::parse_decimal(body)
207        };
208        parsed.map(|mut v| {
209            if neg {
210                v.negative = !v.negative;
211            }
212            v.normalize()
213        })
214    }
215
216    /// 指定基数(2〜16)の桁列をパース。
217    fn parse_radix(digits: &str, radix: u32) -> Option<Self> {
218        if digits.is_empty() {
219            return None;
220        }
221        let mut acc = BigInt::zero();
222        let base = BigInt::from_i64(radix as i64);
223        for ch in digits.chars() {
224            if ch == '_' {
225                continue;
226            }
227            let d = ch.to_digit(radix)?;
228            acc = acc.mul(&base).add(&BigInt::from_i64(d as i64));
229        }
230        Some(acc)
231    }
232
233    /// 絶対値の大小比較。
234    fn cmp_magnitude(&self, other: &Self) -> Ordering {
235        if self.limbs.len() != other.limbs.len() {
236            return self.limbs.len().cmp(&other.limbs.len());
237        }
238        // 上位リムから比較。
239        for i in (0..self.limbs.len()).rev() {
240            if self.limbs[i] != other.limbs[i] {
241                return self.limbs[i].cmp(&other.limbs[i]);
242            }
243        }
244        Ordering::Equal
245    }
246
247    /// 符号込みの全順序比較。
248    #[allow(clippy::should_implement_trait)]
249    pub fn cmp(&self, other: &Self) -> Ordering {
250        match (self.negative, other.negative) {
251            (false, true) => Ordering::Greater,
252            (true, false) => Ordering::Less,
253            (false, false) => self.cmp_magnitude(other),
254            (true, true) => other.cmp_magnitude(self),
255        }
256    }
257
258    /// 絶対値の加算(符号は無視)。
259    fn add_magnitude(a: &[u32], b: &[u32]) -> Vec<u32> {
260        let mut out = Vec::with_capacity(a.len().max(b.len()) + 1);
261        let mut carry: u64 = 0;
262        let n = a.len().max(b.len());
263        for i in 0..n {
264            let av = *a.get(i).unwrap_or(&0) as u64;
265            let bv = *b.get(i).unwrap_or(&0) as u64;
266            let sum = av + bv + carry;
267            out.push((sum & 0xFFFF_FFFF) as u32);
268            carry = sum >> 32;
269        }
270        if carry > 0 {
271            out.push(carry as u32);
272        }
273        out
274    }
275
276    /// 絶対値の減算 a - b(a >= b を前提)。
277    fn sub_magnitude(a: &[u32], b: &[u32]) -> Vec<u32> {
278        let mut out = Vec::with_capacity(a.len());
279        let mut borrow: i64 = 0;
280        for (i, &av_u) in a.iter().enumerate() {
281            let av = av_u as i64;
282            let bv = *b.get(i).unwrap_or(&0) as i64;
283            let mut diff = av - bv - borrow;
284            if diff < 0 {
285                diff += 1 << 32;
286                borrow = 1;
287            } else {
288                borrow = 0;
289            }
290            out.push((diff & 0xFFFF_FFFF) as u32);
291        }
292        out
293    }
294
295    /// 加算。
296    pub fn add(&self, other: &Self) -> Self {
297        if self.negative == other.negative {
298            // 同符号: 絶対値を足して符号は据え置き。
299            BigInt {
300                negative: self.negative,
301                limbs: Self::add_magnitude(&self.limbs, &other.limbs),
302            }
303            .normalize()
304        } else {
305            // 異符号: 絶対値の大きい方から小さい方を引く。
306            match self.cmp_magnitude(other) {
307                Ordering::Equal => BigInt::zero(),
308                Ordering::Greater => BigInt {
309                    negative: self.negative,
310                    limbs: Self::sub_magnitude(&self.limbs, &other.limbs),
311                }
312                .normalize(),
313                Ordering::Less => BigInt {
314                    negative: other.negative,
315                    limbs: Self::sub_magnitude(&other.limbs, &self.limbs),
316                }
317                .normalize(),
318            }
319        }
320    }
321
322    /// 減算。
323    pub fn sub(&self, other: &Self) -> Self {
324        // a - b = a + (-b)
325        let neg_other = BigInt {
326            negative: !other.negative,
327            limbs: other.limbs.clone(),
328        }
329        .normalize();
330        self.add(&neg_other)
331    }
332
333    /// 符号反転。
334    pub fn neg(&self) -> Self {
335        if self.is_zero() {
336            return BigInt::zero();
337        }
338        BigInt {
339            negative: !self.negative,
340            limbs: self.limbs.clone(),
341        }
342    }
343
344    /// 絶対値。
345    pub fn abs(&self) -> Self {
346        BigInt {
347            negative: false,
348            limbs: self.limbs.clone(),
349        }
350    }
351
352    /// 乗算(素朴な O(n*m) 筆算)。
353    pub fn mul(&self, other: &Self) -> Self {
354        if self.is_zero() || other.is_zero() {
355            return BigInt::zero();
356        }
357        let mut out = alloc::vec![0u32; self.limbs.len() + other.limbs.len()];
358        for (i, &a) in self.limbs.iter().enumerate() {
359            let mut carry: u64 = 0;
360            for (j, &b) in other.limbs.iter().enumerate() {
361                let idx = i + j;
362                let cur = out[idx] as u64 + (a as u64) * (b as u64) + carry;
363                out[idx] = (cur & 0xFFFF_FFFF) as u32;
364                carry = cur >> 32;
365            }
366            // 端のキャリーを伝播。
367            let mut k = i + other.limbs.len();
368            while carry > 0 {
369                let cur = out[k] as u64 + carry;
370                out[k] = (cur & 0xFFFF_FFFF) as u32;
371                carry = cur >> 32;
372                k += 1;
373            }
374        }
375        BigInt {
376            negative: self.negative != other.negative,
377            limbs: out,
378        }
379        .normalize()
380    }
381
382    /// 絶対値どうしの除算 → (商, 剰余) を絶対値で返す。
383    /// 素朴なビット単位の long division(速度より明快さを優先)。
384    fn divmod_magnitude(a: &[u32], b: &[u32]) -> (Vec<u32>, Vec<u32>) {
385        // b == 0 は呼び出し側で弾く前提。
386        let dividend = BigInt {
387            negative: false,
388            limbs: a.to_vec(),
389        }
390        .normalize();
391        let divisor = BigInt {
392            negative: false,
393            limbs: b.to_vec(),
394        }
395        .normalize();
396        if dividend.cmp_magnitude(&divisor) == Ordering::Less {
397            return (Vec::new(), dividend.limbs);
398        }
399        // ビット長を求める。
400        let total_bits = dividend.limbs.len() * 32;
401        let mut quotient = BigInt::zero();
402        let mut remainder = BigInt::zero();
403        let one = BigInt::from_i64(1);
404        for i in (0..total_bits).rev() {
405            // remainder <<= 1
406            remainder = remainder.shl_bits(1);
407            // remainder |= bit i of dividend
408            let limb = i / 32;
409            let bit = i % 32;
410            if (dividend.limbs[limb] >> bit) & 1 == 1 {
411                remainder = remainder.add(&one);
412            }
413            if remainder.cmp_magnitude(&divisor) != Ordering::Less {
414                remainder = BigInt {
415                    negative: false,
416                    limbs: Self::sub_magnitude(&remainder.limbs, &divisor.limbs),
417                }
418                .normalize();
419                quotient = quotient.set_bit(i);
420            }
421        }
422        (quotient.normalize().limbs, remainder.normalize().limbs)
423    }
424
425    /// 絶対値を左へ bit ビットシフト(内部用、符号は維持)。
426    fn shl_bits(&self, bits: usize) -> Self {
427        if self.is_zero() || bits == 0 {
428            return self.clone();
429        }
430        let limb_shift = bits / 32;
431        let bit_shift = bits % 32;
432        let mut out = alloc::vec![0u32; self.limbs.len() + limb_shift + 1];
433        for (i, &v) in self.limbs.iter().enumerate() {
434            let val = (v as u64) << bit_shift;
435            out[i + limb_shift] |= (val & 0xFFFF_FFFF) as u32;
436            out[i + limb_shift + 1] |= (val >> 32) as u32;
437        }
438        BigInt {
439            negative: self.negative,
440            limbs: out,
441        }
442        .normalize()
443    }
444
445    /// 絶対値を右へ bit ビットシフト(内部用、符号は維持。算術的切り捨て)。
446    fn shr_bits(&self, bits: usize) -> Self {
447        if self.is_zero() || bits == 0 {
448            return self.clone();
449        }
450        let limb_shift = bits / 32;
451        let bit_shift = bits % 32;
452        if limb_shift >= self.limbs.len() {
453            return BigInt::zero();
454        }
455        let mut out = alloc::vec![0u32; self.limbs.len() - limb_shift];
456        for (i, slot) in out.iter_mut().enumerate() {
457            let lo = self.limbs[i + limb_shift] >> bit_shift;
458            let hi = if bit_shift > 0 && i + limb_shift + 1 < self.limbs.len() {
459                self.limbs[i + limb_shift + 1] << (32 - bit_shift)
460            } else {
461                0
462            };
463            *slot = lo | hi;
464        }
465        BigInt {
466            negative: self.negative,
467            limbs: out,
468        }
469        .normalize()
470    }
471
472    /// ビット i を 1 にした新しい値を返す(絶対値操作・内部用)。
473    fn set_bit(&self, i: usize) -> Self {
474        let limb = i / 32;
475        let bit = i % 32;
476        let mut limbs = self.limbs.clone();
477        if limb >= limbs.len() {
478            limbs.resize(limb + 1, 0);
479        }
480        limbs[limb] |= 1 << bit;
481        BigInt {
482            negative: self.negative,
483            limbs,
484        }
485    }
486
487    /// 除算(商)。ゼロ除算は None。商は 0 方向への切り捨て(truncation)。
488    pub fn div(&self, other: &Self) -> Option<Self> {
489        if other.is_zero() {
490            return None;
491        }
492        let (q, _) = Self::divmod_magnitude(&self.limbs, &other.limbs);
493        Some(
494            BigInt {
495                negative: self.negative != other.negative,
496                limbs: q,
497            }
498            .normalize(),
499        )
500    }
501
502    /// 剰余。ゼロ除算は None。符号は被除数に従う(ECMAScript 準拠)。
503    pub fn rem(&self, other: &Self) -> Option<Self> {
504        if other.is_zero() {
505            return None;
506        }
507        let (_, r) = Self::divmod_magnitude(&self.limbs, &other.limbs);
508        Some(
509            BigInt {
510                negative: self.negative,
511                limbs: r,
512            }
513            .normalize(),
514        )
515    }
516
517    /// 累乗(指数は非負 BigInt のみ。負指数は None)。二乗法で計算。
518    pub fn pow(&self, exp: &Self) -> Option<Self> {
519        if exp.negative {
520            return None;
521        }
522        if exp.is_zero() {
523            return Some(BigInt::from_i64(1));
524        }
525        let mut result = BigInt::from_i64(1);
526        let mut base = self.clone();
527        let mut e = exp.clone();
528        let two = BigInt::from_i64(2);
529        while !e.is_zero() {
530            // e が奇数なら result *= base
531            let (_, r) = Self::divmod_magnitude(&e.limbs, &two.limbs);
532            let odd = !r.is_empty();
533            if odd {
534                result = result.mul(&base);
535            }
536            base = base.mul(&base);
537            e = e.shr_bits(1).abs();
538        }
539        Some(result)
540    }
541
542    /// 十進文字列化。
543    pub fn to_decimal_string(&self) -> String {
544        if self.is_zero() {
545            return String::from("0");
546        }
547        // 絶対値を 10^9 チャンクで割り続けて下位から桁を得る。
548        let mut digits_rev: Vec<u32> = Vec::new();
549        let chunk = BigInt::from_i64(1_000_000_000);
550        let mut cur = self.abs();
551        while !cur.is_zero() {
552            let (q, r) = Self::divmod_magnitude(&cur.limbs, &chunk.limbs);
553            let rem_val = limbs_to_u64(&r) as u32;
554            digits_rev.push(rem_val);
555            cur = BigInt {
556                negative: false,
557                limbs: q,
558            }
559            .normalize();
560        }
561        let mut s = String::new();
562        if self.negative {
563            s.push('-');
564        }
565        // 最上位チャンクは前ゼロなし、それ以降は 9 桁ゼロ詰め。
566        for (i, chunk_val) in digits_rev.iter().rev().enumerate() {
567            if i == 0 {
568                s.push_str(&alloc::format!("{}", chunk_val));
569            } else {
570                s.push_str(&alloc::format!("{:09}", chunk_val));
571            }
572        }
573        s
574    }
575
576    /// `radix` 進(2〜36)の文字列化(`(123n).toString(16)` は "7b")。10 進は `to_decimal_string`。
577    pub fn to_radix_string(&self, radix: u32) -> String {
578        if radix == 10 || !(2..=36).contains(&radix) {
579            return self.to_decimal_string();
580        }
581        if self.is_zero() {
582            return String::from("0");
583        }
584        let base = BigInt::from_u64(radix as u64);
585        let mut digits_rev: Vec<char> = Vec::new();
586        let mut cur = self.abs();
587        while !cur.is_zero() {
588            let (q, r) = Self::divmod_magnitude(&cur.limbs, &base.limbs);
589            let d = limbs_to_u64(&r) as u32;
590            digits_rev.push(core::char::from_digit(d, radix).unwrap_or('0'));
591            cur = BigInt { negative: false, limbs: q }.normalize();
592        }
593        let mut s = String::new();
594        if self.negative {
595            s.push('-');
596        }
597        s.extend(digits_rev.iter().rev());
598        s
599    }
600
601    /// 近似的に f64 へ変換(Number(bigint) 用。大きすぎる値は Infinity に近づく)。
602    pub fn to_f64(&self) -> f64 {
603        let mut result = 0.0_f64;
604        let base = 4294967296.0_f64; // 2^32
605        for &limb in self.limbs.iter().rev() {
606            result = result * base + (limb as f64);
607        }
608        if self.negative {
609            -result
610        } else {
611            result
612        }
613    }
614
615    /// 1 かどうか(絶対値が 1 で正)。
616    pub fn is_one(&self) -> bool {
617        !self.negative && self.limbs.len() == 1 && self.limbs[0] == 1
618    }
619
620    /// このビット長(絶対値を表すのに必要な最小ビット数)。ゼロは 0。
621    fn bit_length(&self) -> usize {
622        match self.limbs.last() {
623            None => 0,
624            Some(&top) => (self.limbs.len() - 1) * 32 + (32 - top.leading_zeros() as usize),
625        }
626    }
627
628    /// 指定リム数の「2 の補数表現」をリトルエンディアンの u32 列で返す。
629    /// 負数は ~|x| + 1 を width リム幅で計算する。正数はゼロ拡張。
630    fn to_twos_complement(&self, width: usize) -> Vec<u32> {
631        let mut out = alloc::vec![0u32; width];
632        for (i, slot) in out.iter_mut().enumerate() {
633            *slot = *self.limbs.get(i).unwrap_or(&0);
634        }
635        if self.negative {
636            // ビット反転して +1。
637            for slot in out.iter_mut() {
638                *slot = !*slot;
639            }
640            let mut carry = 1u64;
641            for slot in out.iter_mut() {
642                let v = *slot as u64 + carry;
643                *slot = (v & 0xFFFF_FFFF) as u32;
644                carry = v >> 32;
645                if carry == 0 {
646                    break;
647                }
648            }
649        }
650        out
651    }
652
653    /// width リム幅の 2 の補数表現(リトルエンディアン)から BigInt を復元する。
654    /// 最上位ビットが 1 なら負数とみなす。
655    fn from_twos_complement(mut limbs: Vec<u32>) -> Self {
656        let negative = limbs
657            .last()
658            .map(|&top| (top >> 31) & 1 == 1)
659            .unwrap_or(false);
660        if negative {
661            // 2 の補数を反転して大きさを得る: |x| = ~bits + 1。
662            for slot in limbs.iter_mut() {
663                *slot = !*slot;
664            }
665            let mut carry = 1u64;
666            for slot in limbs.iter_mut() {
667                let v = *slot as u64 + carry;
668                *slot = (v & 0xFFFF_FFFF) as u32;
669                carry = v >> 32;
670                if carry == 0 {
671                    break;
672                }
673            }
674        }
675        BigInt { negative, limbs }.normalize()
676    }
677
678    /// 2 つの値のビット演算に必要なリム幅(両者の絶対値ビット長 + 符号ビット余裕)。
679    fn bitop_width(&self, other: &Self) -> usize {
680        let bits = self.bit_length().max(other.bit_length());
681        // 符号ビットのために 1 ビット余分に確保し、リム単位へ切り上げる。
682        (bits / 32) + 2
683    }
684
685    /// ビット AND(2 の補数の無限長セマンティクス)。
686    pub fn bitand(&self, other: &Self) -> Self {
687        let w = self.bitop_width(other);
688        let a = self.to_twos_complement(w);
689        let b = other.to_twos_complement(w);
690        let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x & y).collect();
691        Self::from_twos_complement(out)
692    }
693
694    /// ビット OR。
695    pub fn bitor(&self, other: &Self) -> Self {
696        let w = self.bitop_width(other);
697        let a = self.to_twos_complement(w);
698        let b = other.to_twos_complement(w);
699        let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x | y).collect();
700        Self::from_twos_complement(out)
701    }
702
703    /// ビット XOR。
704    pub fn bitxor(&self, other: &Self) -> Self {
705        let w = self.bitop_width(other);
706        let a = self.to_twos_complement(w);
707        let b = other.to_twos_complement(w);
708        let out: Vec<u32> = a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect();
709        Self::from_twos_complement(out)
710    }
711
712    /// ビット NOT(~x = -(x+1)、2 の補数の恒等式)。
713    pub fn bitnot(&self) -> Self {
714        // ~x = -x - 1
715        self.neg().sub(&BigInt::from_i64(1))
716    }
717
718    /// 左シフト(count は非負 i64。符号は保存、絶対値を count ビット左へ)。
719    pub fn shl(&self, count: i64) -> Self {
720        if count < 0 {
721            return self.shr(-count);
722        }
723        let shifted = self.shl_bits(count as usize);
724        BigInt {
725            negative: self.negative,
726            limbs: shifted.limbs,
727        }
728        .normalize()
729    }
730
731    /// 右シフト(算術シフト = 床方向。負数では -infinity 方向へ丸める ECMAScript 準拠)。
732    pub fn shr(&self, count: i64) -> Self {
733        if count < 0 {
734            return self.shl(-count);
735        }
736        let n = count as usize;
737        if !self.negative {
738            // 正数は単純な論理右シフト。
739            let shifted = self.shr_bits(n);
740            return BigInt {
741                negative: false,
742                limbs: shifted.limbs,
743            }
744            .normalize();
745        }
746        // 負数の算術右シフトは床関数: floor(x / 2^n)。
747        // |x| を n ビット右シフトし、切り捨てた下位ビットが非ゼロなら -1 する。
748        let full_limbs = n / 32;
749        let rem_bits = n % 32;
750        let mut truncated_bits = false;
751        for &l in self.limbs.iter().take(full_limbs) {
752            if l != 0 {
753                truncated_bits = true;
754                break;
755            }
756        }
757        if !truncated_bits && rem_bits > 0 {
758            if let Some(&l) = self.limbs.get(full_limbs) {
759                let mask = (1u32 << rem_bits) - 1;
760                if (l & mask) != 0 {
761                    truncated_bits = true;
762                }
763            }
764        }
765        let mag = self.shr_bits(n);
766        let mut result = BigInt {
767            negative: true,
768            limbs: mag.limbs,
769        }
770        .normalize();
771        if truncated_bits {
772            // 床方向へさらに 1 引く(負方向に大きくする)。
773            result = result.sub(&BigInt::from_i64(1));
774        }
775        result
776    }
777
778    /// BigInt.asUintN(bits, x): 下位 bits ビットを符号なし整数として解釈。
779    pub fn as_uint_n(&self, bits: u64) -> Self {
780        if bits == 0 {
781            return BigInt::zero();
782        }
783        let full_limbs = (bits / 32) as usize;
784        let rem_bits = (bits % 32) as usize;
785        let width = full_limbs + if rem_bits > 0 { 1 } else { 0 } + 1;
786        let tc = self.to_twos_complement(width);
787        let out_limbs_count = full_limbs + if rem_bits > 0 { 1 } else { 0 };
788        let mut out = alloc::vec![0u32; out_limbs_count];
789        for i in 0..full_limbs {
790            if i < tc.len() {
791                out[i] = tc[i];
792            }
793        }
794        if rem_bits > 0 && full_limbs < tc.len() {
795            let mask = (1u32 << rem_bits) - 1;
796            out[full_limbs] = tc[full_limbs] & mask;
797        }
798        // 符号なしなので最上位に符号ビットが立たないよう、そのまま大きさとして扱う。
799        BigInt {
800            negative: false,
801            limbs: out,
802        }
803        .normalize()
804    }
805
806    /// BigInt.asIntN(bits, x): 下位 bits ビットを符号付き 2 の補数として解釈。
807    pub fn as_int_n(&self, bits: u64) -> Self {
808        if bits == 0 {
809            return BigInt::zero();
810        }
811        let unsigned = self.as_uint_n(bits);
812        // 最上位ビット(bits-1)が立っていれば 2^bits を引いて負数化。
813        let top = (bits - 1) as usize;
814        let limb = top / 32;
815        let bit = top % 32;
816        let is_neg = limb < unsigned.limbs.len() && (unsigned.limbs[limb] >> bit) & 1 == 1;
817        if is_neg {
818            // result = unsigned - 2^bits
819            let two_pow = BigInt::from_i64(1).shl(bits as i64);
820            unsigned.sub(&two_pow)
821        } else {
822            unsigned
823        }
824    }
825
826    /// 下位64ビットを2の補数のビットパターンとして u64 へ切り詰める。
827    /// `DataView.prototype.setBigInt64/setBigUint64` がバイト列へ書き戻す際に使う。
828    pub fn to_u64_truncated(&self) -> u64 {
829        let unsigned = self.as_uint_n(64);
830        let low = *unsigned.limbs.first().unwrap_or(&0) as u64;
831        let high = *unsigned.limbs.get(1).unwrap_or(&0) as u64;
832        low | (high << 32)
833    }
834}
835
836/// リム列(最大 2 リム想定)を u64 に詰める補助。
837fn limbs_to_u64(limbs: &[u32]) -> u64 {
838    let mut v = 0u64;
839    for (i, &l) in limbs.iter().enumerate().take(2) {
840        v |= (l as u64) << (32 * i);
841    }
842    v
843}
844
845/// BigInt 自己テスト。(pass, total) を返す。
846/// 算術・比較・ビット演算・シフト・asIntN/asUintN・パース・文字列化を検証する。
847pub fn selftest() -> (usize, usize) {
848    let mut pass = 0usize;
849    let mut total = 0usize;
850
851    // 文字列等価で検証する小ヘルパ。
852    fn check_str(pass: &mut usize, total: &mut usize, got: &str, want: &str) {
853        *total += 1;
854        if got == want {
855            *pass += 1;
856        }
857    }
858    // 真偽値検証ヘルパ。
859    fn check_bool(pass: &mut usize, total: &mut usize, cond: bool) {
860        *total += 1;
861        if cond {
862            *pass += 1;
863        }
864    }
865    // Option<String> 検証ヘルパ(unwrap を使わずに失敗を None として扱う)。
866    // パース失敗や div/pow の None はそのまま不一致(テスト失敗)になる。
867    fn check_opt(pass: &mut usize, total: &mut usize, got: Option<String>, want: &str) {
868        *total += 1;
869        if got.as_deref() == Some(want) {
870            *pass += 1;
871        }
872    }
873
874    let bi = BigInt::from_i64;
875    let p = &mut pass;
876    let t = &mut total;
877
878    // --- パース & 文字列化 ---
879    check_opt(
880        p,
881        t,
882        BigInt::parse_str("0").map(|b| b.to_decimal_string()),
883        "0",
884    );
885    check_opt(
886        p,
887        t,
888        BigInt::parse_str("12345678901234567890").map(|b| b.to_decimal_string()),
889        "12345678901234567890",
890    );
891    check_opt(
892        p,
893        t,
894        BigInt::parse_str("-98765432109876543210").map(|b| b.to_decimal_string()),
895        "-98765432109876543210",
896    );
897    check_opt(
898        p,
899        t,
900        BigInt::parse_str("0xff").map(|b| b.to_decimal_string()),
901        "255",
902    );
903    check_opt(
904        p,
905        t,
906        BigInt::parse_str("0b1010").map(|b| b.to_decimal_string()),
907        "10",
908    );
909    check_opt(
910        p,
911        t,
912        BigInt::parse_str("0o17").map(|b| b.to_decimal_string()),
913        "15",
914    );
915    check_opt(
916        p,
917        t,
918        BigInt::parse_str("1_000_000").map(|b| b.to_decimal_string()),
919        "1000000",
920    );
921
922    // --- 加減算(桁上がり・桁借り・符号交差)---
923    check_str(p, t, &bi(2).add(&bi(3)).to_decimal_string(), "5");
924    check_opt(
925        p,
926        t,
927        BigInt::parse_str("4294967295").map(|b| b.add(&bi(1)).to_decimal_string()),
928        "4294967296",
929    );
930    check_str(p, t, &bi(5).sub(&bi(8)).to_decimal_string(), "-3");
931    check_str(p, t, &bi(-5).add(&bi(5)).to_decimal_string(), "0");
932    check_opt(
933        p,
934        t,
935        BigInt::parse_str("18446744073709551616").map(|b| b.sub(&bi(1)).to_decimal_string()),
936        "18446744073709551615",
937    );
938
939    // --- 乗算 ---
940    check_str(
941        p,
942        t,
943        &bi(123456789).mul(&bi(987654321)).to_decimal_string(),
944        "121932631112635269",
945    );
946    check_str(p, t, &bi(-7).mul(&bi(6)).to_decimal_string(), "-42");
947    check_opt(
948        p,
949        t,
950        BigInt::parse_str("99999999999999999999").and_then(|a| {
951            BigInt::parse_str("99999999999999999999").map(|b| a.mul(&b).to_decimal_string())
952        }),
953        "9999999999999999999800000000000000000001",
954    );
955
956    // --- 除算・剰余(符号は被除数に従う)---
957    check_opt(
958        p,
959        t,
960        bi(100).div(&bi(7)).map(|b| b.to_decimal_string()),
961        "14",
962    );
963    check_opt(
964        p,
965        t,
966        bi(100).rem(&bi(7)).map(|b| b.to_decimal_string()),
967        "2",
968    );
969    check_opt(
970        p,
971        t,
972        bi(-100).div(&bi(7)).map(|b| b.to_decimal_string()),
973        "-14",
974    );
975    check_opt(
976        p,
977        t,
978        bi(-100).rem(&bi(7)).map(|b| b.to_decimal_string()),
979        "-2",
980    );
981    check_bool(p, t, bi(1).div(&bi(0)).is_none());
982
983    // --- 累乗 ---
984    check_opt(
985        p,
986        t,
987        bi(2).pow(&bi(64)).map(|b| b.to_decimal_string()),
988        "18446744073709551616",
989    );
990    check_opt(p, t, bi(3).pow(&bi(0)).map(|b| b.to_decimal_string()), "1");
991    check_opt(
992        p,
993        t,
994        bi(-2).pow(&bi(3)).map(|b| b.to_decimal_string()),
995        "-8",
996    );
997
998    // --- 比較 ---
999    check_bool(p, t, bi(5).cmp(&bi(7)) == Ordering::Less);
1000    check_bool(p, t, bi(-3).cmp(&bi(-9)) == Ordering::Greater);
1001    check_bool(p, t, bi(42).cmp(&bi(42)) == Ordering::Equal);
1002
1003    // --- ビット演算(正数)---
1004    check_str(
1005        p,
1006        t,
1007        &bi(0b1100).bitand(&bi(0b1010)).to_decimal_string(),
1008        "8",
1009    ); // 0b1000
1010    check_str(
1011        p,
1012        t,
1013        &bi(0b1100).bitor(&bi(0b1010)).to_decimal_string(),
1014        "14",
1015    ); // 0b1110
1016    check_str(
1017        p,
1018        t,
1019        &bi(0b1100).bitxor(&bi(0b1010)).to_decimal_string(),
1020        "6",
1021    ); // 0b0110
1022
1023    // --- ビット演算(負数: 2 の補数の無限長セマンティクス)---
1024    check_str(p, t, &bi(5).bitnot().to_decimal_string(), "-6"); // ~5n == -6n
1025    check_str(p, t, &bi(-1).bitnot().to_decimal_string(), "0"); // ~(-1n) == 0n
1026    check_str(p, t, &bi(-1).bitand(&bi(5)).to_decimal_string(), "5"); // -1n & 5n == 5n
1027    check_str(p, t, &bi(-1).bitor(&bi(5)).to_decimal_string(), "-1"); // -1n | 5n == -1n
1028    check_str(p, t, &bi(-2).bitand(&bi(3)).to_decimal_string(), "2"); // -2n & 3n == 2n
1029    check_str(p, t, &bi(-1).bitxor(&bi(-1)).to_decimal_string(), "0"); // -1n ^ -1n == 0n
1030
1031    // --- シフト ---
1032    check_str(
1033        p,
1034        t,
1035        &bi(1).shl(64).to_decimal_string(),
1036        "18446744073709551616",
1037    );
1038    check_str(p, t, &bi(255).shr(4).to_decimal_string(), "15");
1039    // 負数の算術右シフト(床方向): -8 >> 1 == -4, -7 >> 1 == -4
1040    check_str(p, t, &bi(-8).shr(1).to_decimal_string(), "-4");
1041    check_str(p, t, &bi(-7).shr(1).to_decimal_string(), "-4");
1042    check_str(p, t, &bi(-1).shr(5).to_decimal_string(), "-1");
1043    check_str(
1044        p,
1045        t,
1046        &bi(12345).shl(40).shr(40).to_decimal_string(),
1047        "12345",
1048    );
1049
1050    // --- asUintN / asIntN ---
1051    check_str(p, t, &bi(256).as_uint_n(8).to_decimal_string(), "0");
1052    check_str(p, t, &bi(257).as_uint_n(8).to_decimal_string(), "1");
1053    check_str(p, t, &bi(-1).as_uint_n(8).to_decimal_string(), "255");
1054    check_str(p, t, &bi(255).as_int_n(8).to_decimal_string(), "-1");
1055    check_str(p, t, &bi(128).as_int_n(8).to_decimal_string(), "-128");
1056    check_str(p, t, &bi(127).as_int_n(8).to_decimal_string(), "127");
1057    check_str(p, t, &bi(0x8000).as_int_n(16).to_decimal_string(), "-32768");
1058
1059    // --- f64 変換 ---
1060    check_bool(p, t, bi(9007199254740992).to_f64() == 9007199254740992.0);
1061    check_bool(
1062        p,
1063        t,
1064        BigInt::from_f64(42.0).map(|b| b.to_decimal_string()) == Some(String::from("42")),
1065    );
1066    check_bool(p, t, BigInt::from_f64(1.5).is_none());
1067
1068    (pass, total)
1069}