rhai-bigint 0.1.6

Rhai plugin providing arbitrary-precision BigInt support
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
#![doc = include_str!("../README.md")]

//! Arbitrary-precision BigInt support for Rhai scripts.
//!
//! Provides [`BigIntPackage`] (via `def_package!`) for registering BigInt
//! support into a Rhai [`Engine`](rhai::Engine).

use num_bigint::BigInt;
use rhai::{def_package, plugin::*};

#[export_module]
mod bigint_functions {
    use num_bigint::{BigInt, Sign};
    use num_traits::{FromPrimitive, ToPrimitive, Zero};

    /// Creates a `BigInt` from an integer.
    pub fn parse_bigint(value: i64) -> BigInt {
        value.into()
    }

    /// Creates a `BigInt` from a float by truncating toward zero.
    #[rhai_fn(name = "parse_bigint", return_raw)]
    pub fn parse_bigint_from_float(value: rhai::FLOAT) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        BigInt::from_f64(value)
            .ok_or_else(|| format!("Cannot convert {value} to BigInt: value must be finite").into())
    }

    /// Creates a `BigInt` from a string.
    #[rhai_fn(name = "parse_bigint", return_raw)]
    pub fn parse_bigint_from_str(value: String) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        value
            .parse::<BigInt>()
            .map_err(|e| format!("Failed to create BigInt from string: {e}").into())
    }

    #[rhai_fn(name = "+", pure)]
    pub fn add(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() + r
    }

    #[rhai_fn(name = "-", pure)]
    pub fn sub(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() - r
    }

    #[rhai_fn(name = "*", pure)]
    pub fn mul(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() * r
    }

    #[rhai_fn(name = "/", pure, return_raw)]
    pub fn div(l: &mut BigInt, r: BigInt) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        if r.is_zero() {
            return Err("Division by zero".into());
        }
        Ok(l.clone() / r)
    }

    #[rhai_fn(name = "%", pure, return_raw)]
    pub fn rem(l: &mut BigInt, r: BigInt) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        if r.is_zero() {
            return Err("Modulo by zero".into());
        }
        Ok(l.clone() % r)
    }

    #[rhai_fn(name = "-", pure)]
    pub fn neg(value: &mut BigInt) -> BigInt {
        -value.clone()
    }

    /// Raises a `BigInt` to an integer power. The exponent must be non-negative
    /// and fit in a `u32`; returns an error otherwise.
    #[rhai_fn(name = "**", pure, return_raw)]
    pub fn pow(base: &mut BigInt, exp: i64) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        let exp_u32 = u32::try_from(exp).map_err(|_| -> Box<rhai::EvalAltResult> {
            format!("Exponent must be a non-negative integer that fits in u32, got {exp}").into()
        })?;
        Ok(base.clone().pow(exp_u32))
    }

    #[rhai_fn(name = "&", pure)]
    pub fn bitand(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() & r
    }

    #[rhai_fn(name = "|", pure)]
    pub fn bitor(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() | r
    }

    #[rhai_fn(name = "^", pure)]
    pub fn bitxor(l: &mut BigInt, r: BigInt) -> BigInt {
        l.clone() ^ r
    }

    fn validate_shift_amount(shift: i64) -> Result<u32, Box<rhai::EvalAltResult>> {
        if shift < 0 {
            return Err(format!("Shift amount must be non-negative, got {shift}").into());
        }

        u32::try_from(shift).map_err(|_| -> Box<rhai::EvalAltResult> {
            format!("Shift amount is too large, must be at most {}", u32::MAX).into()
        })
    }

    /// Left-shifts a `BigInt` by `shift` bits. `shift` must be non-negative and fit in `u32`.
    #[rhai_fn(name = "<<", pure, return_raw)]
    pub fn shl(value: &mut BigInt, shift: i64) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        let shift_u32 = validate_shift_amount(shift)?;
        Ok(value.clone() << shift_u32)
    }

    /// Right-shifts a `BigInt` by `shift` bits. `shift` must be non-negative and fit in `u32`.
    #[rhai_fn(name = ">>", pure, return_raw)]
    pub fn shr(value: &mut BigInt, shift: i64) -> Result<BigInt, Box<rhai::EvalAltResult>> {
        let shift_u32 = validate_shift_amount(shift)?;
        Ok(value.clone() >> shift_u32)
    }

    #[rhai_fn(name = "==", pure)]
    pub fn eq(l: &mut BigInt, r: BigInt) -> bool {
        *l == r
    }

    #[rhai_fn(name = "!=", pure)]
    pub fn ne(l: &mut BigInt, r: BigInt) -> bool {
        *l != r
    }

    #[rhai_fn(name = "<", pure)]
    pub fn lt(l: &mut BigInt, r: BigInt) -> bool {
        *l < r
    }

    #[rhai_fn(name = "<=", pure)]
    pub fn le(l: &mut BigInt, r: BigInt) -> bool {
        *l <= r
    }

    #[rhai_fn(name = ">", pure)]
    pub fn gt(l: &mut BigInt, r: BigInt) -> bool {
        *l > r
    }

    #[rhai_fn(name = ">=", pure)]
    pub fn ge(l: &mut BigInt, r: BigInt) -> bool {
        *l >= r
    }

    /// Converts a `BigInt` to its decimal string representation.
    #[rhai_fn(name = "to_string", pure)]
    pub fn to_string(value: &mut BigInt) -> String {
        value.to_string()
    }

    /// Converts a `BigInt` to a `0x`-prefixed lowercase hex string.
    /// Negative values are prefixed with `-0x`.
    #[rhai_fn(name = "to_hex", pure)]
    pub fn to_hex(value: &mut BigInt) -> String {
        let hex = format!("{:x}", value.magnitude());
        if value.sign() == Sign::Minus {
            format!("-0x{hex}")
        } else {
            format!("0x{hex}")
        }
    }

    /// Converts a `BigInt` to a float, returning an error if the value
    /// is too large to represent as a finite float.
    #[rhai_fn(name = "to_float", pure, return_raw)]
    pub fn to_float(value: &mut BigInt) -> Result<rhai::FLOAT, Box<rhai::EvalAltResult>> {
        value
            .to_f64()
            .map(|f| f as rhai::FLOAT)
            .filter(|f| f.is_finite())
            .ok_or_else(|| "BigInt value is too large to represent as a finite float".into())
    }
}

def_package! {
    /// Arbitrary-precision BigInt for Rhai: `bigint()` constructor plus
    /// arithmetic (`+`, `-`, `*`, `/`, `%`), unary negation (`-`), and comparison operators.
    pub BigIntPackage(lib) {
        lib.set_custom_type::<BigInt>("BigInt");
        combine_with_exported_module!(lib, "bigint", bigint_functions);
    }
}

#[cfg(test)]
mod tests {
    use rhai::{Engine, packages::Package};

    use super::*;

    #[test]
    fn test_rhai_integration() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: BigInt = engine.eval("parse_bigint(42)").unwrap();
        assert_eq!(result.to_string(), "42");

        let result: BigInt = engine
            .eval("parse_bigint(\"123456789012345678901234567890\")")
            .unwrap();
        assert_eq!(result.to_string(), "123456789012345678901234567890");

        let result: BigInt = engine.eval("parse_bigint(42) + parse_bigint(58)").unwrap();
        assert_eq!(result.to_string(), "100");

        let result: bool = engine.eval("parse_bigint(50) > parse_bigint(42)").unwrap();
        assert!(result);

        let result: bool = engine.eval("parse_bigint(42) == parse_bigint(42)").unwrap();
        assert!(result);

        let result: bool = engine
            .eval("parse_bigint(42) != parse_bigint(100)")
            .unwrap();
        assert!(result);
    }

    #[test]
    fn test_core_functionality() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: BigInt = engine
            .eval("parse_bigint(1000000000000000000) + parse_bigint(2000000000000000000)")
            .unwrap();
        assert_eq!(result.to_string(), "3000000000000000000");

        let result: BigInt = engine
            .eval("parse_bigint(5000000000000000000) - parse_bigint(1000000000000000000)")
            .unwrap();
        assert_eq!(result.to_string(), "4000000000000000000");

        let result: BigInt = engine
            .eval("parse_bigint(1000000) * parse_bigint(1000000)")
            .unwrap();
        assert_eq!(result.to_string(), "1000000000000");

        let result: BigInt = engine
            .eval("parse_bigint(1000000000000) / parse_bigint(1000000)")
            .unwrap();
        assert_eq!(result.to_string(), "1000000");

        let result: BigInt = engine.eval("parse_bigint(10) % parse_bigint(3)").unwrap();
        assert_eq!(result.to_string(), "1");

        let result: BigInt = engine.eval("-parse_bigint(42)").unwrap();
        assert_eq!(result.to_string(), "-42");
    }

    #[test]
    fn test_error_handling() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result = engine.eval::<BigInt>("parse_bigint(\"not_a_number\")");
        assert!(result.is_err());

        let result = engine.eval::<BigInt>("parse_bigint(42) / parse_bigint(0)");
        assert!(result.is_err());

        let result = engine.eval::<BigInt>("parse_bigint(42) % parse_bigint(0)");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_bigint_from_f64() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        // fractional part is truncated toward zero
        let result: BigInt = engine.eval("parse_bigint(1.5)").unwrap();
        assert_eq!(result.to_string(), "1");

        let result: BigInt = engine.eval("parse_bigint(-2.9)").unwrap();
        assert_eq!(result.to_string(), "-2");

        // exactly representable whole-number floats convert exactly
        let result: BigInt = engine.eval("parse_bigint(42.0)").unwrap();
        assert_eq!(result.to_string(), "42");

        // large float that exceeds i64 range
        let result: BigInt = engine.eval("parse_bigint(1e30)").unwrap();
        assert_eq!(result.to_string(), "1000000000000000019884624838656");
    }

    #[test]
    fn test_parse_bigint_from_f64_errors() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result = engine.eval::<BigInt>("parse_bigint(1.0 / 0.0)");
        assert!(result.is_err(), "infinity should be rejected");

        let result = engine.eval::<BigInt>("parse_bigint(0.0 / 0.0)");
        assert!(result.is_err(), "NaN should be rejected");
    }

    #[test]
    fn test_to_string() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: String = engine.eval("parse_bigint(42).to_string()").unwrap();
        assert_eq!(result, "42");

        let result: String = engine.eval("parse_bigint(-99).to_string()").unwrap();
        assert_eq!(result, "-99");

        let result: String = engine
            .eval("parse_bigint(\"123456789012345678901234567890\").to_string()")
            .unwrap();
        assert_eq!(result, "123456789012345678901234567890");
    }

    #[test]
    fn test_to_hex() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: String = engine.eval("parse_bigint(255).to_hex()").unwrap();
        assert_eq!(result, "0xff");

        let result: String = engine.eval("parse_bigint(0).to_hex()").unwrap();
        assert_eq!(result, "0x0");

        let result: String = engine.eval("parse_bigint(-255).to_hex()").unwrap();
        assert_eq!(result, "-0xff");

        let result: String = engine.eval("parse_bigint(256).to_hex()").unwrap();
        assert_eq!(result, "0x100");
    }

    #[test]
    fn test_exponentiation() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: BigInt = engine.eval("parse_bigint(2) ** 10").unwrap();
        assert_eq!(result.to_string(), "1024");

        let result: BigInt = engine.eval("parse_bigint(10) ** 18").unwrap();
        assert_eq!(result.to_string(), "1000000000000000000");

        let result: BigInt = engine.eval("parse_bigint(-3) ** 3").unwrap();
        assert_eq!(result.to_string(), "-27");

        let result: BigInt = engine.eval("parse_bigint(5) ** 0").unwrap();
        assert_eq!(result.to_string(), "1");

        // negative exponent should be rejected
        let result = engine.eval::<BigInt>("parse_bigint(2) ** -1");
        assert!(result.is_err(), "negative exponent should be rejected");
    }

    #[test]
    fn test_bitwise_operators() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        // AND
        let result: BigInt = engine
            .eval("parse_bigint(0b1100) & parse_bigint(0b1010)")
            .unwrap();
        assert_eq!(result.to_string(), "8"); // 0b1000

        let result: BigInt = engine.eval("parse_bigint(255) & parse_bigint(15)").unwrap();
        assert_eq!(result.to_string(), "15");

        // OR
        let result: BigInt = engine
            .eval("parse_bigint(0b1100) | parse_bigint(0b1010)")
            .unwrap();
        assert_eq!(result.to_string(), "14"); // 0b1110

        let result: BigInt = engine.eval("parse_bigint(240) | parse_bigint(15)").unwrap();
        assert_eq!(result.to_string(), "255");

        // XOR
        let result: BigInt = engine
            .eval("parse_bigint(0b1100) ^ parse_bigint(0b1010)")
            .unwrap();
        assert_eq!(result.to_string(), "6"); // 0b0110

        let result: BigInt = engine
            .eval("parse_bigint(255) ^ parse_bigint(255)")
            .unwrap();
        assert_eq!(result.to_string(), "0");

        // Left shift
        let result: BigInt = engine.eval("parse_bigint(1) << 10").unwrap();
        assert_eq!(result.to_string(), "1024");

        let result: BigInt = engine.eval("parse_bigint(1) << 64").unwrap();
        assert_eq!(result.to_string(), "18446744073709551616");

        // Right shift
        let result: BigInt = engine.eval("parse_bigint(1024) >> 3").unwrap();
        assert_eq!(result.to_string(), "128");

        let result: BigInt = engine.eval("parse_bigint(1) >> 1").unwrap();
        assert_eq!(result.to_string(), "0");

        // Negative shift amount should be rejected
        let result = engine.eval::<BigInt>("parse_bigint(1) << -1");
        assert!(result.is_err(), "negative left-shift should be rejected");

        let result = engine.eval::<BigInt>("parse_bigint(1) >> -1");
        assert!(result.is_err(), "negative right-shift should be rejected");
    }

    #[test]
    fn test_to_float() {
        let mut engine = Engine::new();
        BigIntPackage::new().register_into_engine(&mut engine);

        let result: rhai::FLOAT = engine.eval("parse_bigint(42).to_float()").unwrap();
        assert_eq!(result, 42.0);

        let result: rhai::FLOAT = engine.eval("parse_bigint(-7).to_float()").unwrap();
        assert_eq!(result, -7.0);

        // value too large to be finite in f64
        let result = engine.eval::<rhai::FLOAT>(
            "parse_bigint(\"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\").to_float()"
        );
        assert!(result.is_err(), "overflow to infinity should be rejected");
    }
}