lexical_util/
api.rs

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
//! Implement string conversion routines in a single trait.

// NOTE:
//  We use macros to define the traits, rather than implement here
//  since we can't define traits for types when both are defined outside
//  the current crate, including in workspaces.

// FROM LEXICAL

/// Define FromLexical trait.
#[macro_export]
#[cfg(feature = "parse")]
macro_rules! from_lexical {
    () => {
        /// Trait for numerical types that can be parsed from bytes.
        pub trait FromLexical: lexical_util::num::Number {
            /// Checked parser for a string-to-number conversion.
            ///
            /// This method parses the entire string, returning an error if
            /// any invalid digits are found during parsing. Returns a `Result`
            /// containing either the parsed value, or an error containing
            /// any errors that occurred during parsing.
            ///
            /// * `bytes`   - Slice containing a numeric string.
            fn from_lexical(bytes: &[u8]) -> lexical_util::result::Result<Self>;

            /// Checked parser for a string-to-number conversion.
            ///
            /// This method parses until an invalid digit is found (or the end
            /// of the string), returning the number of processed digits
            /// and the parsed value until that point. Returns a `Result`
            /// containing either the parsed value and the number of processed
            /// digits, or an error containing any errors that occurred during
            /// parsing.
            ///
            /// * `bytes`   - Slice containing a numeric string.
            fn from_lexical_partial(bytes: &[u8]) -> lexical_util::result::Result<(Self, usize)>;
        }
    };
}

/// Define FromLexicalWithOptions trait.
#[macro_export]
#[cfg(feature = "parse")]
macro_rules! from_lexical_with_options {
    () => {
        /// Trait for numerical types that can be parsed from bytes with custom options.
        ///
        /// The `Options` type specifies the configurable options to provide.
        pub trait FromLexicalWithOptions: lexical_util::num::Number {
            /// Custom formatting options for parsing a number.
            type Options: lexical_util::options::ParseOptions;

            /// Checked parser for a string-to-number conversion.
            ///
            /// This method parses the entire string, returning an error if
            /// any invalid digits are found during parsing. The parsing
            /// is dictated by the options, which specifies special
            /// float strings, required float components, digit separators,
            /// exponent characters, and more. Returns a `Result` containing
            /// either the parsed value, or an error containing any errors
            /// that occurred during parsing.
            ///
            /// * `FORMAT`  - Flags and characters designating the number grammar.
            /// * `bytes`   - Slice containing a numeric string.
            /// * `options` - Options to dictate number parsing.
            ///
            /// The `FORMAT` packed struct is built using [`NumberFormatBuilder`].
            /// Any invalid number format will prevent parsing, returning
            /// the appropriate format error. If you are unsure which format
            /// to use, use [`STANDARD`].
            ///
            /// [`NumberFormatBuilder`]: lexical_util::format::NumberFormatBuilder
            /// [`STANDARD`]: lexical_util::format::STANDARD
            fn from_lexical_with_options<const FORMAT: u128>(
                bytes: &[u8],
                options: &Self::Options,
            ) -> lexical_util::result::Result<Self>;

            /// Checked parser for a string-to-number conversion.
            ///
            /// This method parses until an invalid digit is found (or the end
            /// of the string), returning the number of processed digits
            /// and the parsed value until that point. Returns a `Result`
            /// containing either the parsed value and the number of
            /// processed digits, or an error containing any errors that
            /// occurred during parsing.
            ///
            /// * `FORMAT`  - Flags and characters designating the number grammar.
            /// * `bytes`   - Slice containing a numeric string.
            /// * `options` - Options to dictate number parsing.
            ///
            /// The `FORMAT` packed struct is built using [`NumberFormatBuilder`].
            /// Any invalid number format will prevent parsing, returning
            /// the appropriate format error. If you are unsure which format
            /// to use, use [`STANDARD`].
            ///
            /// [`NumberFormatBuilder`]: lexical_util::format::NumberFormatBuilder
            /// [`STANDARD`]: lexical_util::format::STANDARD
            fn from_lexical_partial_with_options<const FORMAT: u128>(
                bytes: &[u8],
                options: &Self::Options,
            ) -> lexical_util::result::Result<(Self, usize)>;
        }
    };
}

// TO LEXICAL

/// Define ToLexical trait.
#[macro_export]
#[cfg(feature = "write")]
macro_rules! to_lexical {
    () => {
        /// Trait for numerical types that can be serialized to bytes.
        ///
        /// To determine the number of bytes required to serialize a value to
        /// string, check the associated constants from a required trait:
        /// - [`FORMATTED_SIZE`]
        /// - [`FORMATTED_SIZE_DECIMAL`]
        ///
        /// [`FORMATTED_SIZE`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE
        /// [`FORMATTED_SIZE_DECIMAL`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE_DECIMAL
        pub trait ToLexical:
            lexical_util::constants::FormattedSize + lexical_util::num::Number
        {
            /// Serializer for a number-to-string conversion.
            ///
            /// Returns a subslice of the input buffer containing the written bytes,
            /// starting from the same address in memory as the input slice.
            ///
            /// * `value`   - Number to serialize.
            /// * `bytes`   - Buffer to write number to.
            ///
            /// # Safety
            ///
            /// Safe as long as the caller has provided a buffer of at least
            /// [`FORMATTED_SIZE_DECIMAL`] elements. If a smaller buffer is
            /// provided, a buffer overflow is very likely.
            ///
            /// [`FORMATTED_SIZE_DECIMAL`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE_DECIMAL
            unsafe fn to_lexical_unchecked<'a>(self, bytes: &'a mut [u8]) -> &'a mut [u8];

            /// Serializer for a number-to-string conversion.
            ///
            /// Returns a subslice of the input buffer containing the written bytes,
            /// starting from the same address in memory as the input slice.
            ///
            /// * `value`   - Number to serialize.
            /// * `bytes`   - Buffer to write number to.
            ///
            /// # Panics
            ///
            /// Panics if the buffer is not of sufficient size. The caller
            /// must provide a slice of sufficient size. In order to ensure
            /// the function will not panic, ensure the buffer has at least
            /// [`FORMATTED_SIZE_DECIMAL`] elements.
            ///
            /// [`FORMATTED_SIZE_DECIMAL`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE_DECIMAL
            fn to_lexical<'a>(self, bytes: &'a mut [u8]) -> &'a mut [u8];
        }
    };
}

/// Define ToLexicalWithOptions trait.
#[macro_export]
#[cfg(feature = "write")]
macro_rules! to_lexical_with_options {
    () => {
        /// Trait for numerical types that can be serialized to bytes with custom options.
        ///
        /// To determine the number of bytes required to serialize a value to
        /// string, check the associated constants from a required trait:
        /// - [`FORMATTED_SIZE`]
        /// - [`FORMATTED_SIZE_DECIMAL`]
        ///
        /// The `Options` type specifies the configurable options to provide.
        ///
        /// [`FORMATTED_SIZE`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE
        /// [`FORMATTED_SIZE_DECIMAL`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE_DECIMAL
        pub trait ToLexicalWithOptions:
            lexical_util::constants::FormattedSize + lexical_util::num::Number
        {
            /// Custom formatting options for writing a number.
            type Options: lexical_util::options::WriteOptions;

            /// Serializer for a number-to-string conversion.
            ///
            /// Returns a subslice of the input buffer containing the written bytes,
            /// starting from the same address in memory as the input slice.
            ///
            /// * `FORMAT`  - Flags and characters designating the number grammar.
            /// * `value`   - Number to serialize.
            /// * `bytes`   - Buffer to write number to.
            /// * `options` - Options for number formatting.
            ///
            /// # Safety
            ///
            /// Safe as long as the caller has provided a buffer of at least
            /// [`FORMATTED_SIZE`] elements. If a smaller buffer is provided, a
            /// buffer overflow is very likely. If you are changing the
            /// number significant digits written, the exponent break points,
            /// or disabling scientific notation, you will need a larger buffer
            /// than the one provided. An upper limit on the buffer size can
            /// then be determined using [`WriteOptions::buffer_size`]. If you
            /// are not using `min_significant_digits`, 1200 bytes is always
            /// enough to hold the the output for a custom radix, and `400`
            /// is always enough for decimal strings.
            ///
            /// # Panics
            ///
            /// **Floats Only**
            ///
            /// These panics are only when using uncommon features for float
            /// writing, represent configuration errors, so runtime error
            /// handling is not provided.
            ///
            /// Panics if the provided number format is invalid, or if the
            /// mantissa radix is not equal to the exponent base
            /// and the mantissa radix/exponent base combinations are
            /// not in the following list:
            ///
            /// - `4, 2`
            /// - `8, 2`
            /// - `16, 2`
            /// - `32, 2`
            /// - `16, 4`
            ///
            /// Panics as well if the NaN or Inf string provided to the writer
            /// is disabled, but the value provided is NaN or Inf, respectively.
            ///
            /// [`WriteOptions::buffer_size`]: lexical_util::options::WriteOptions::buffer_size
            /// [`FORMATTED_SIZE`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE
            unsafe fn to_lexical_with_options_unchecked<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                options: &Self::Options,
            ) -> &'a mut [u8];

            /// Serializer for a number-to-string conversion.
            ///
            /// Returns a subslice of the input buffer containing the written bytes,
            /// starting from the same address in memory as the input slice.
            ///
            /// * `FORMAT`  - Flags and characters designating the number grammar.
            /// * `value`   - Number to serialize.
            /// * `bytes`   - Buffer to write number to.
            /// * `options` - Options for number formatting.
            ///
            /// # Panics
            ///
            /// Panics if the buffer is not of sufficient size. The caller
            /// must provide a slice of sufficient size. In order to ensure
            /// the function will not panic, ensure the buffer has at least
            /// [`FORMATTED_SIZE`] elements. If you are changing the
            /// number significant digits written, the exponent break points,
            /// or disabling scientific notation, you will need a larger buffer
            /// than the one provided. An upper limit on the buffer size can
            /// then be determined using [`WriteOptions::buffer_size`]. If you
            /// are not using `min_significant_digits`, 1200 bytes is always
            /// enough to hold the the output for a custom radix, and `400`
            /// is always enough for decimal strings.
            ///
            /// **Floats Only**
            ///
            /// These panics are only when using uncommon features for float
            /// writing, represent configuration errors, so runtime error
            /// handling is not provided.
            ///
            /// Also panics if the provided number format is invalid, or
            /// if the mantissa radix is not equal to the exponent base
            /// and the mantissa radix/exponent base combinations are
            /// not in the following list:
            ///
            /// - `4, 2`
            /// - `8, 2`
            /// - `16, 2`
            /// - `32, 2`
            /// - `16, 4`
            ///
            /// Panics as well if the NaN or Inf string provided to the writer
            /// is disabled, but the value provided is NaN or Inf, respectively.
            ///
            /// [`WriteOptions::buffer_size`]: lexical_util::options::WriteOptions::buffer_size
            /// [`FORMATTED_SIZE`]: lexical_util::constants::FormattedSize::FORMATTED_SIZE
            fn to_lexical_with_options<'a, const FORMAT: u128>(
                self,
                bytes: &'a mut [u8],
                options: &Self::Options,
            ) -> &'a mut [u8];
        }
    };
}