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
//! Implements the algorithm in terms of the lexical API.

#![doc(hidden)]

use crate::options::Options;
use crate::write::WriteInteger;
use lexical_util::assert::{assert_buffer, debug_assert_buffer};
use lexical_util::format::{NumberFormat, STANDARD};
use lexical_util::num::SignedInteger;
use lexical_util::{to_lexical, to_lexical_with_options};

// UNSIGNED

/// Callback for unsigned integer formatter.
///
/// # Safety
///
/// Safe as long as the buffer can hold `FORMATTED_SIZE` elements
/// (or `FORMATTED_SIZE_DECIMAL` for decimal).
#[inline]
unsafe fn unsigned<Narrow, Wide, const FORMAT: u128>(value: Narrow, buffer: &mut [u8]) -> usize
where
    Narrow: WriteInteger,
    Wide: WriteInteger,
{
    let format = NumberFormat::<FORMAT> {};
    if cfg!(feature = "format") && format.required_mantissa_sign() {
        // SAFETY: safe as long as there is at least `FORMATTED_SIZE` elements.
        unsafe {
            index_unchecked_mut!(buffer[0]) = b'+';
            let buffer = &mut index_unchecked_mut!(buffer[1..]);
            value.write_mantissa::<Wide, FORMAT>(buffer) + 1
        }
    } else {
        // SAFETY: safe as long as there is at least `FORMATTED_SIZE` elements.
        unsafe { value.write_mantissa::<Wide, FORMAT>(buffer) }
    }
}

// SIGNED

/// Callback for signed integer formatter.
///
/// # Safety
///
/// Safe as long as the buffer can hold `FORMATTED_SIZE` elements
/// (or `FORMATTED_SIZE_DECIMAL` for decimal).
#[inline]
unsafe fn signed<Narrow, Wide, Unsigned, const FORMAT: u128>(
    value: Narrow,
    buffer: &mut [u8],
) -> usize
where
    Narrow: SignedInteger,
    Wide: SignedInteger,
    Unsigned: WriteInteger,
{
    let format = NumberFormat::<FORMAT> {};
    if value < Narrow::ZERO {
        // Need to cast the value to the same size as unsigned type, since if
        // the value is **exactly** `Narrow::MIN`, and it it is then cast
        // as the wrapping negative as the unsigned value, a wider type
        // will have a very different value.
        let value = Wide::as_cast(value);
        let unsigned = Unsigned::as_cast(value.wrapping_neg());
        // SAFETY: safe as long as there is at least `FORMATTED_SIZE` elements.
        unsafe {
            index_unchecked_mut!(buffer[0]) = b'-';
            let buffer = &mut index_unchecked_mut!(buffer[1..]);
            unsigned.write_mantissa::<Unsigned, FORMAT>(buffer) + 1
        }
    } else if cfg!(feature = "format") && format.required_mantissa_sign() {
        let unsigned = Unsigned::as_cast(value);
        // SAFETY: safe as long as there is at least `FORMATTED_SIZE` elements.
        unsafe {
            index_unchecked_mut!(buffer[0]) = b'+';
            let buffer = &mut index_unchecked_mut!(buffer[1..]);
            unsigned.write_mantissa::<Unsigned, FORMAT>(buffer) + 1
        }
    } else {
        let unsigned = Unsigned::as_cast(value);
        // SAFETY: safe as long as there is at least `FORMATTED_SIZE` elements.
        unsafe { unsigned.write_mantissa::<Unsigned, FORMAT>(buffer) }
    }
}

// API

// Implement ToLexical for numeric type.
macro_rules! unsigned_to_lexical {
    ($($narrow:tt $wide:tt $(, #[$meta:meta])? ; )*) => ($(
        impl ToLexical for $narrow {
            $(#[$meta:meta])?
            unsafe fn to_lexical_unchecked<'a>(self, bytes: &'a mut [u8])
                -> &'a mut [u8]
            {
                debug_assert_buffer::<$narrow>(10, bytes.len());
                // SAFETY: safe if `bytes.len() > Self::FORMATTED_SIZE_DECIMAL`.
                unsafe {
                    let len = unsigned::<$narrow, $wide, { STANDARD }>(self, bytes);
                    &mut index_unchecked_mut!(bytes[..len])
                }
            }

            $(#[$meta:meta])?
            fn to_lexical<'a>(self, bytes: &'a mut [u8])
                -> &'a mut [u8]
            {
                assert_buffer::<$narrow>(10, bytes.len());
                // SAFETY: safe since `bytes.len() > Self::FORMATTED_SIZE_DECIMAL`.
                unsafe { self.to_lexical_unchecked(bytes) }
            }
        }

        impl ToLexicalWithOptions for $narrow {
            type Options = Options;

            $(#[$meta:meta])?
            unsafe fn to_lexical_with_options_unchecked<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                _: &Self::Options,
            ) -> &'a mut [u8]
            {
                debug_assert_buffer::<$narrow>(NumberFormat::<{ FORMAT }>::RADIX, bytes.len());
                assert!(NumberFormat::<{ FORMAT }> {}.is_valid());
                // SAFETY: safe if `bytes.len() > Self::FORMATTED_SIZE`.
                unsafe {
                    let len = unsigned::<$narrow, $wide, FORMAT>(self, bytes);
                    &mut index_unchecked_mut!(bytes[..len])
                }
            }

            $(#[$meta:meta])?
            fn to_lexical_with_options<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                options: &Self::Options,
            ) -> &'a mut [u8]
            {
                assert_buffer::<$narrow>(NumberFormat::<{ FORMAT }>::RADIX, bytes.len());
                assert!(NumberFormat::<{ FORMAT }> {}.is_valid());
                // SAFETY: safe since `bytes.len() > Self::FORMATTED_SIZE`.
                unsafe { self.to_lexical_with_options_unchecked::<FORMAT>(bytes, options) }
            }
        }
    )*)
}

to_lexical! {}
to_lexical_with_options! {}
unsigned_to_lexical! {
    u8 u32 ;
    u16 u32 ;
    u32 u32 ;
    u64 u64 ;
    u128 u128 ;
}

#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
unsigned_to_lexical! { usize u32 ; }

#[cfg(target_pointer_width = "64")]
unsigned_to_lexical! { usize u64 ; }

// Implement ToLexical for numeric type.
macro_rules! signed_to_lexical {
    ($($narrow:tt $wide:tt $unsigned:tt $(, #[$meta:meta])? ; )*) => ($(
        impl ToLexical for $narrow {
            $(#[$meta:meta])?
            unsafe fn to_lexical_unchecked<'a>(self, bytes: &'a mut [u8])
                -> &'a mut [u8]
            {
                debug_assert_buffer::<$narrow>(10, bytes.len());
                // SAFETY: safe if `bytes.len() > Self::FORMATTED_SIZE_DECIMAL`.
                unsafe {
                    let len = signed::<$narrow, $wide, $unsigned, { STANDARD }>(self, bytes);
                    &mut index_unchecked_mut!(bytes[..len])
                }
            }

            $(#[$meta:meta])?
            fn to_lexical<'a>(self, bytes: &'a mut [u8])
                -> &'a mut [u8]
            {
                assert_buffer::<$narrow>(10, bytes.len());
                // SAFETY: safe since `bytes.len() > Self::FORMATTED_SIZE_DECIMAL`.
                unsafe { self.to_lexical_unchecked(bytes) }
            }
        }

        impl ToLexicalWithOptions for $narrow {
            type Options = Options;

            $(#[$meta:meta])?
            unsafe fn to_lexical_with_options_unchecked<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                _: &Self::Options,
            ) -> &'a mut [u8]
            {
                debug_assert_buffer::<$narrow>(NumberFormat::<{ FORMAT }>::RADIX, bytes.len());
                assert!(NumberFormat::<{ FORMAT }> {}.is_valid());
                // SAFETY: safe if `bytes.len() > Self::FORMATTED_SIZE`.
                unsafe {
                    let len = signed::<$narrow, $wide, $unsigned, FORMAT>(self, bytes);
                    &mut index_unchecked_mut!(bytes[..len])
                }
            }

            $(#[$meta:meta])?
            fn to_lexical_with_options<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                options: &Self::Options,
            ) -> &'a mut [u8]
            {
                assert_buffer::<$narrow>(NumberFormat::<{ FORMAT }>::RADIX, bytes.len());
                assert!(NumberFormat::<{ FORMAT }> {}.is_valid());
                // SAFETY: safe since `bytes.len() > Self::FORMATTED_SIZE`.
                unsafe { self.to_lexical_with_options_unchecked::<FORMAT>(bytes, options) }
            }
        }
    )*)
}

signed_to_lexical! {
    i8 i32 u32 ;
    i16 i32 u32 ;
    i32 i32 u32 ;
    i64 i64 u64 ;
    i128 i128 u128 ;
}

#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
signed_to_lexical! { isize i32 u32 ; }

#[cfg(target_pointer_width = "64")]
signed_to_lexical! { isize i64 u64 ; }