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
use super::iter_basic::CharsStream;
use crate::plugin::*;
use crate::{def_package, FnPtr, ImmutableString, SmartString, INT, MAX_USIZE_INT};
use std::any::TypeId;
use std::fmt::{Binary, LowerHex, Octal, Write};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;

#[cfg(not(feature = "no_index"))]
use crate::Array;

#[cfg(not(feature = "no_object"))]
use crate::Map;

/// Standard pretty-print function.
///
/// This function is called to convert any type into text format for display.
pub const FUNC_TO_STRING: &str = "to_string";

/// Standard debug-print function.
///
/// This function is called to convert any type into text format suitable for debugging.
pub const FUNC_TO_DEBUG: &str = "to_debug";

def_package! {
    /// Package of basic string utilities (e.g. printing)
    pub BasicStringPackage(lib) {
        lib.set_standard_lib(true);

        combine_with_exported_module!(lib, "print_debug", print_debug_functions);
        combine_with_exported_module!(lib, "number_formatting", number_formatting);
        combine_with_exported_module!(lib, "char", char_functions);

        // Register characters iterator
        lib.set_iterator::<CharsStream>();

        lib.set_iter(TypeId::of::<ImmutableString>(), |value| Box::new(
            CharsStream::new(value.cast::<ImmutableString>().as_str(), 0, MAX_USIZE_INT).map(Into::into)
        ));
    }
}

/// Print a value using a named function.
#[inline]
pub fn print_with_func(
    fn_name: &str,
    ctx: &NativeCallContext,
    value: &mut Dynamic,
) -> ImmutableString {
    match ctx.call_native_fn_raw(fn_name, true, &mut [value]) {
        Ok(result) if result.is_string() => result.into_immutable_string().unwrap(),
        Ok(result) => ctx.engine().map_type_name(result.type_name()).into(),
        Err(_) => {
            let mut buf = SmartString::new_const();
            match fn_name {
                FUNC_TO_DEBUG => write!(&mut buf, "{value:?}").unwrap(),
                _ => write!(&mut buf, "{value}").unwrap(),
            }
            ctx.engine().map_type_name(&buf).into()
        }
    }
}

#[export_module]
mod print_debug_functions {
    /// Convert the value of the `item` into a string.
    #[rhai_fn(name = "print", pure)]
    pub fn print_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString {
        print_with_func(FUNC_TO_STRING, &ctx, item)
    }
    /// Convert the value of the `item` into a string.
    #[rhai_fn(name = "to_string", pure)]
    pub fn to_string_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{item}").unwrap();
        ctx.engine().map_type_name(&buf).into()
    }
    /// Convert the value of the `item` into a string in debug format.
    #[rhai_fn(name = "debug", pure)]
    pub fn debug_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString {
        print_with_func(FUNC_TO_DEBUG, &ctx, item)
    }
    /// Convert the value of the `item` into a string in debug format.
    #[rhai_fn(name = "to_debug", pure)]
    pub fn to_debug_generic(ctx: NativeCallContext, item: &mut Dynamic) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{item:?}").unwrap();
        ctx.engine().map_type_name(&buf).into()
    }

    /// Return the empty string.
    #[rhai_fn(name = "print", name = "debug")]
    pub fn print_empty_string(ctx: NativeCallContext) -> ImmutableString {
        ctx.engine().const_empty_string()
    }

    /// Return the `string`.
    #[rhai_fn(name = "print", name = "to_string")]
    pub const fn print_string(string: ImmutableString) -> ImmutableString {
        string
    }
    /// Convert the string into debug format.
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_string(string: &str) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{string:?}").unwrap();
        buf.into()
    }

    /// Return the character into a string.
    #[rhai_fn(name = "print", name = "to_string")]
    pub fn print_char(character: char) -> ImmutableString {
        let mut buf = SmartString::new_const();
        buf.push(character);
        buf.into()
    }
    /// Convert the string into debug format.
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_char(character: char) -> ImmutableString {
        let mut buf = SmartString::new_const();
        buf.push(character);
        buf.into()
    }

    /// Convert the function pointer into a string in debug format.
    #[rhai_fn(name = "debug", name = "to_debug", pure)]
    pub fn debug_fn_ptr(f: &mut FnPtr) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{f}").unwrap();
        buf.into()
    }

    /// Return the boolean value into a string.
    #[rhai_fn(name = "print", name = "to_string")]
    pub fn print_bool(value: bool) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{value}").unwrap();
        buf.into()
    }
    /// Convert the boolean value into a string in debug format.
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_bool(value: bool) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{value:?}").unwrap();
        buf.into()
    }

    /// Return the empty string.
    #[allow(unused_variables)]
    #[rhai_fn(name = "print", name = "to_string")]
    pub fn print_unit(ctx: NativeCallContext, unit: ()) -> ImmutableString {
        ctx.engine().const_empty_string()
    }
    /// Convert the unit into a string in debug format.
    #[allow(unused_variables)]
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_unit(unit: ()) -> ImmutableString {
        "()".into()
    }

    /// Convert the value of `number` into a string.
    #[cfg(not(feature = "no_float"))]
    #[rhai_fn(name = "print", name = "to_string")]
    pub fn print_f64(number: f64) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{}", crate::types::FloatWrapper::new(number)).unwrap();
        buf.into()
    }
    /// Convert the value of `number` into a string.
    #[cfg(not(feature = "no_float"))]
    #[rhai_fn(name = "print", name = "to_string")]
    pub fn print_f32(number: f32) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{}", crate::types::FloatWrapper::new(number)).unwrap();
        buf.into()
    }
    /// Convert the value of `number` into a string.
    #[cfg(not(feature = "no_float"))]
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_f64(number: f64) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{:?}", crate::types::FloatWrapper::new(number)).unwrap();
        buf.into()
    }
    /// Convert the value of `number` into a string.
    #[cfg(not(feature = "no_float"))]
    #[rhai_fn(name = "debug", name = "to_debug")]
    pub fn debug_f32(number: f32) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{:?}", crate::types::FloatWrapper::new(number)).unwrap();
        buf.into()
    }

    /// Convert the array into a string.
    #[cfg(not(feature = "no_index"))]
    #[rhai_fn(
        name = "print",
        name = "to_string",
        name = "debug",
        name = "to_debug",
        pure
    )]
    pub fn format_array(ctx: NativeCallContext, array: &mut Array) -> ImmutableString {
        let len = array.len();
        let mut result = SmartString::new_const();
        result.push_str("[");

        array.iter_mut().enumerate().for_each(|(i, x)| {
            result.push_str(&print_with_func(FUNC_TO_DEBUG, &ctx, x));
            if i < len - 1 {
                result.push_str(", ");
            }
        });

        result.push_str("]");
        result.into()
    }

    /// Convert the object map into a string.
    #[cfg(not(feature = "no_object"))]
    #[rhai_fn(
        name = "print",
        name = "to_string",
        name = "debug",
        name = "to_debug",
        pure
    )]
    pub fn format_map(ctx: NativeCallContext, map: &mut Map) -> ImmutableString {
        let len = map.len();
        let mut result = SmartString::new_const();
        result.push_str("#{");

        map.iter_mut().enumerate().for_each(|(i, (k, v))| {
            write!(
                result,
                "{:?}: {}{}",
                k,
                &print_with_func(FUNC_TO_DEBUG, &ctx, v),
                if i < len - 1 { ", " } else { "" }
            )
            .unwrap();
        });

        result.push_str("}");
        result.into()
    }
}

#[export_module]
mod number_formatting {
    fn to_hex<T: LowerHex>(value: T) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{value:x}").unwrap();
        buf.into()
    }
    fn to_octal<T: Octal>(value: T) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{value:o}").unwrap();
        buf.into()
    }
    fn to_binary<T: Binary>(value: T) -> ImmutableString {
        let mut buf = SmartString::new_const();
        write!(&mut buf, "{value:b}").unwrap();
        buf.into()
    }

    /// Convert the `value` into a string in hex format.
    #[rhai_fn(name = "to_hex")]
    pub fn int_to_hex(value: INT) -> ImmutableString {
        to_hex(value)
    }
    /// Convert the `value` into a string in octal format.
    #[rhai_fn(name = "to_octal")]
    pub fn int_to_octal(value: INT) -> ImmutableString {
        to_octal(value)
    }
    /// Convert the `value` into a string in binary format.
    #[rhai_fn(name = "to_binary")]
    pub fn int_to_binary(value: INT) -> ImmutableString {
        to_binary(value)
    }

    #[cfg(not(feature = "only_i32"))]
    #[cfg(not(feature = "only_i64"))]
    pub mod numbers {
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn u8_to_hex(value: u8) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn u16_to_hex(value: u16) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn u32_to_hex(value: u32) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn u64_to_hex(value: u64) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn i8_to_hex(value: i8) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn i16_to_hex(value: i16) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn i32_to_hex(value: i32) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in hex format.
        #[rhai_fn(name = "to_hex")]
        pub fn i64_to_hex(value: i64) -> ImmutableString {
            to_hex(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn u8_to_octal(value: u8) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn u16_to_octal(value: u16) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn u32_to_octal(value: u32) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn u64_to_octal(value: u64) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn i8_to_octal(value: i8) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn i16_to_octal(value: i16) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn i32_to_octal(value: i32) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in octal format.
        #[rhai_fn(name = "to_octal")]
        pub fn i64_to_octal(value: i64) -> ImmutableString {
            to_octal(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn u8_to_binary(value: u8) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn u16_to_binary(value: u16) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn u32_to_binary(value: u32) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn u64_to_binary(value: u64) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn i8_to_binary(value: i8) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn i16_to_binary(value: i16) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn i32_to_binary(value: i32) -> ImmutableString {
            to_binary(value)
        }
        /// Convert the `value` into a string in binary format.
        #[rhai_fn(name = "to_binary")]
        pub fn i64_to_binary(value: i64) -> ImmutableString {
            to_binary(value)
        }

        #[cfg(not(target_family = "wasm"))]
        pub mod num_128 {
            /// Convert the `value` into a string in hex format.
            #[rhai_fn(name = "to_hex")]
            pub fn u128_to_hex(value: u128) -> ImmutableString {
                to_hex(value)
            }
            /// Convert the `value` into a string in hex format.
            #[rhai_fn(name = "to_hex")]
            pub fn i128_to_hex(value: i128) -> ImmutableString {
                to_hex(value)
            }
            /// Convert the `value` into a string in octal format.
            #[rhai_fn(name = "to_octal")]
            pub fn u128_to_octal(value: u128) -> ImmutableString {
                to_octal(value)
            }
            /// Convert the `value` into a string in octal format.
            #[rhai_fn(name = "to_octal")]
            pub fn i128_to_octal(value: i128) -> ImmutableString {
                to_octal(value)
            }
            /// Convert the `value` into a string in binary format.
            #[rhai_fn(name = "to_binary")]
            pub fn u128_to_binary(value: u128) -> ImmutableString {
                to_binary(value)
            }
            /// Convert the `value` into a string in binary format.
            #[rhai_fn(name = "to_binary")]
            pub fn i128_to_binary(value: i128) -> ImmutableString {
                to_binary(value)
            }
        }
    }
}

#[export_module]
mod char_functions {
    /// Convert the Unicode character into a 32-bit integer value.
    pub const fn to_int(ch: char) -> INT {
        (ch as u32) as INT
    }
}