rune/modules/num.rs
1//! Working with numbers.
2
3use core::num::{ParseFloatError, ParseIntError};
4
5use crate as rune;
6use crate::alloc;
7use crate::alloc::fmt::TryWrite;
8use crate::runtime::Formatter;
9use crate::{ContextError, Module};
10
11/// Working with numbers.
12///
13/// This module provides types generic for working over numbers, such as errors
14/// when a number cannot be parsed.
15#[rune::module(::std::num)]
16pub fn module() -> Result<Module, ContextError> {
17 let mut module = Module::from_meta(self::module__meta)?;
18
19 module.ty::<ParseFloatError>()?;
20 module.function_meta(parse_float_error_display_fmt)?;
21 module.function_meta(parse_float_error_debug_fmt)?;
22
23 module.ty::<ParseIntError>()?;
24 module.function_meta(parse_int_error_display_fmt)?;
25 module.function_meta(parse_int_error_debug_fmt)?;
26
27 Ok(module)
28}
29
30/// Write why a float could not be parsed.
31///
32/// # Examples
33///
34/// ```rune
35/// let text = if let Err(error) = f64::parse("x") {
36/// format!("{error}")
37/// } else {
38/// ""
39/// };
40///
41/// assert_eq!(text, "invalid float literal");
42/// ```
43#[rune::function(instance, protocol = DISPLAY_FMT)]
44fn parse_float_error_display_fmt(error: &ParseFloatError, f: &mut Formatter) -> alloc::Result<()> {
45 write!(f, "{error}")
46}
47
48/// Write a debug representation of why a float could not be parsed.
49///
50/// # Examples
51///
52/// ```rune
53/// let text = if let Err(error) = f64::parse("x") {
54/// format!("{error:?}")
55/// } else {
56/// ""
57/// };
58///
59/// assert!(text.starts_with("ParseFloatError"));
60/// ```
61#[rune::function(instance, protocol = DEBUG_FMT)]
62fn parse_float_error_debug_fmt(error: &ParseFloatError, f: &mut Formatter) -> alloc::Result<()> {
63 write!(f, "{error:?}")
64}
65
66/// Write why an integer could not be parsed.
67///
68/// # Examples
69///
70/// ```rune
71/// let text = if let Err(error) = i64::parse("x") {
72/// format!("{error}")
73/// } else {
74/// ""
75/// };
76///
77/// assert_eq!(text, "invalid digit found in string");
78/// ```
79#[rune::function(instance, protocol = DISPLAY_FMT)]
80fn parse_int_error_display_fmt(error: &ParseIntError, f: &mut Formatter) -> alloc::Result<()> {
81 write!(f, "{error}")
82}
83
84/// Write a debug representation of why an integer could not be parsed.
85///
86/// # Examples
87///
88/// ```rune
89/// let text = if let Err(error) = i64::parse("x") {
90/// format!("{error:?}")
91/// } else {
92/// ""
93/// };
94///
95/// assert!(text.starts_with("ParseIntError"));
96/// ```
97#[rune::function(instance, protocol = DEBUG_FMT)]
98fn parse_int_error_debug_fmt(error: &ParseIntError, f: &mut Formatter) -> alloc::Result<()> {
99 write!(f, "{error:?}")
100}