Debian Codegraph @

README.md

raw symbols SCIP
1 # lexical
2
3 High-performance numeric conversion routines for use in a `no_std` environment. This does not depend on any standard library features, nor a system allocator. Comprehensive benchmarks can be found at [lexical-benchmarks](https://github.com/Alexhuszagh/lexical-benchmarks).
4
5 **Similar Projects**
6
7 If you want a minimal, performant float parser, recent versions of the Rust standard library should be [sufficient](https://github.com/rust-lang/rust/pull/86761). For high-performance integer formatters, look at [itoa](https://docs.rs/itoa/latest/itoa/). The [metrics](#metrics) section contains a detailed comparison of various crates and their performance in comparison to lexical. Lexical is the currently fastest Rust number formatter and parser, and is tested against:
8 - [itoa](https://crates.io/crates/itoa)
9 - [dtoa](https://crates.io/crates/dtoa)
10 - [ryu](https://crates.io/crates/ryu)
11 - Rust core library
12
13 **Table of Contents**
14
15 - [Getting Started](#getting-started)
16 - [Partial/Complete Parsers](#partialcomplete-parsers)
17 - [no_std](#no_std)
18 - [Features](#features)
19 - [Customization](#customization)
20 - [Number Format API](#number-format-api)
21 - [Options API](#options-api)
22 - [Documentation](#documentation)
23 - [Validation](#validation)
24 - [Metrics](#metrics)
25 - [Safety](#safety)
26 - [Platform Support](#platform-support)
27 - [Versioning and Version Support](#versioning-and-version-support)
28 - [Changelog](#changelog)
29 - [License](#license)
30 - [Contributing](#contributing)
31
32 ## Getting Started
33
34 Add lexical to your `Cargo.toml`:
35
36 ```toml
37 [dependencies]
38 lexical-core = "^1.0"
39 ```
40
41 And get started using lexical:
42
43 ```rust
44 // Number to string
45 use lexical_core::BUFFER_SIZE;
46 let mut buffer = [b'0'; BUFFER_SIZE];
47 lexical_core::write(3.0, &mut buffer); // "3.0", always has a fraction suffix,
48 lexical_core::write(3, &mut buffer); // "3"
49
50 // String to number.
51 let i: i32 = lexical_core::parse("3")?; // Ok(3), auto-type deduction.
52 let f: f32 = lexical_core::parse("3.5")?; // Ok(3.5)
53 let d: f64 = lexical_core::parse("3.5")?; // Ok(3.5), error checking parse.
54 let d: f64 = lexical_core::parse("3a")?; // Err(Error(_)), failed to parse.
55 ```
56
57 In order to use lexical in generic code, the trait bounds `FromLexical` (for `parse`) and `ToLexical` (for `to_string`) are provided.
58
59 ```rust
60 /// Multiply a value in a string by multiplier, and serialize to string.
61 fn mul_2<T>(value: &str, multiplier: T)
62 -> Result<String, lexical_core::Error>
63 where
64 T: lexical_core::ToLexical + lexical_core::FromLexical,
65 {
66 let value: T = lexical_core::parse(value.as_bytes())?;
67 let mut buffer = [b'0'; lexical_core::BUFFER_SIZE];
68 let bytes = lexical_core::write(value * multiplier, &mut buffer);
69 Ok(String::from_utf8(bytes).unwrap())
70 }
71 ```
72
73 ## Partial/Complete Parsers
74
75 Lexical has both partial and complete parsers: the complete parsers ensure the entire buffer is used while parsing, without ignoring trailing characters, while the partial parsers parse as many characters as possible, returning both the parsed value and the number of parsed digits. Upon encountering an error, lexical will return an error indicating both the error type and the index at which the error occurred inside the buffer.
76
77 **Complete Parsers**
78
79 ```rust
80 // This will return Err(Error::InvalidDigit(3)), indicating
81 // the first invalid character occurred at the index 3 in the input
82 // string (the space character).
83 let x: i32 = lexical_core::parse(b"123 456")?;
84 ```
85
86 **Partial Parsers**
87
88 ```rust
89 // This will return Ok((123, 3)), indicating that 3 digits were successfully
90 // parsed, and that the returned value is `123`.
91 let (x, count): (i32, usize) = lexical_core::parse_partial(b"123 456")?;
92 ```
93
94 ## no_std
95
96 `lexical-core` does not depend on a standard library, nor a system allocator. To use `lexical-core` in a [`no_std`] environment, add the following to `Cargo.toml`:
97
98 [`no_std`]: <https://docs.rust-embedded.org/book/intro/no-std.html>
99
100 ```toml
101 [dependencies.lexical-core]
102 version = "1.0.0"
103 default-features = false
104 # Can select only desired parsing/writing features.
105 features = ["write-integers", "write-floats", "parse-integers", "parse-floats"]
106 ```
107
108 And get started using `lexical-core`:
109
110 ```rust
111 // A constant for the maximum number of bytes a formatter will write.
112 use lexical_core::BUFFER_SIZE;
113 let mut buffer = [b'0'; BUFFER_SIZE];
114
115 // Number to string. The underlying buffer must be a slice of bytes.
116 let count = lexical_core::write(3.0, &mut buffer);
117 assert_eq!(buffer[..count], b"3.0");
118 let count = lexical_core::write(3i32, &mut buffer);
119 assert_eq!(buffer[..count], b"3");
120
121 // String to number. The input must be a slice of bytes.
122 let i: i32 = lexical_core::parse(b"3")?; // Ok(3), auto-type deduction.
123 let f: f32 = lexical_core::parse(b"3.5")?; // Ok(3.5)
124 let d: f64 = lexical_core::parse(b"3.5")?; // Ok(3.5), error checking parse.
125 let d: f64 = lexical_core::parse(b"3a")?; // Err(Error(_)), failed to parse.
126 ```
127
128 ## Features
129
130 Lexical feature-gates each numeric conversion routine, resulting in faster compile times if certain numeric conversions. These features can be enabled/disabled for both `lexical-core` (which does not require a system allocator) and `lexical`. By default, all conversions are enabled.
131
132 - **parse-floats**: &ensp; Enable string-to-float conversions.
133 - **parse-integers**: &ensp; Enable string-to-integer conversions.
134 - **write-floats**: &ensp; Enable float-to-string conversions.
135 - **write-integers**: &ensp; Enable integer-to-string conversions.
136
137 Lexical is highly customizable, and contains numerous other optional features:
138
139 - **std**: &ensp; Enable use of the Rust standard library (enabled by default).
140 - **power-of-two**: &ensp; Enable conversions to and from non-decimal strings.
141 <blockquote>With power_of_two enabled, the radixes <code>{2, 4, 8, 10, 16, and 32}</code> are valid, otherwise, only <code>10</code> is valid. This enables common conversions to/from hexadecimal integers/floats, without requiring large pre-computed tables for other radixes.</blockquote>
142 - **radix**: &ensp; Allow conversions to and from non-decimal strings.
143 <blockquote>With radix enabled, any radix from <code>2</code> to <code>36</code> (inclusive) is valid, otherwise, only <code>10</code> is valid.</blockquote>
144 - **format**: &ensp; Customize acceptable number formats for number parsing and writing.
145 <blockquote>With format enabled, the number format is dictated through bitflags and masks packed into a <code>u128</code>. These dictate the valid syntax of parsed and written numbers, including enabling digit separators, requiring integer or fraction digits, and toggling case-sensitive exponent characters.</blockquote>
146 - **compact**: &ensp; Optimize for binary size at the expense of performance.
147 <blockquote>This minimizes the use of pre-computed tables, producing significantly smaller binaries.</blockquote>
148 - **f16**: &ensp; Add support for numeric conversions to-and-from 16-bit floats.
149 <blockquote>Adds <code>f16</code>, a half-precision IEEE-754 floating-point type, and <code>bf16</code>, the Brain Float 16 type, and numeric conversions to-and-from these floats. Note that since these are storage formats, and therefore do not have native arithmetic operations, all conversions are done using an intermediate <code>f32</code>.</blockquote>
150
151 To ensure memory safety, we extensively fuzz the all numeric conversion routines. See the [Safety](#safety) section below for more information.
152
153 Lexical also places a heavy focus on code bloat: with algorithms both optimized for performance and size. By default, this focuses on performance, however, using the `compact` feature, you can also opt-in to reduced code size at the cost of performance. The compact algorithms minimize the use of pre-computed tables and other optimizations at a major cost to performance.
154
155 ## Customization
156
157 Lexical is extensively customizable to support parsing numbers from a wide variety of programming languages, such as `1_2_3`. However, lexical takes the concept of "you don't pay for what you don't use" seriously: enabling the `format` feature does not affect the performance of parsing regular numbers: only those with digit separators.
158
159 > ⚠ **WARNING:** When changing the number of significant digits written, disabling the use of exponent notation, or changing exponent notation thresholds, `BUFFER_SIZE` may be insufficient to hold the resulting output. `WriteOptions::buffer_size_const` will provide a correct upper bound on the number of bytes written. If a buffer of insufficient length is provided, `lexical-core` will panic.
160
161 Every language has competing specifications for valid numerical input, meaning a number parser for Rust will incorrectly accept or reject input for different programming or data languages. For example:
162
163 ```rust
164 // Valid in Rust strings.
165 // Not valid in JSON.
166 let f: f64 = lexical_core::parse(b"3.e7")?; // 3e7
167
168 // Let's only accept JSON floats.
169 const JSON: u128 = lexical_core::format::JSON;
170 const OPTIONS: ParseFloatOptions = ParseFloatOptions::new();
171 let f: f64 = lexical_core::parse_with_options::<_, JSON>(b"3.0e7", &OPTIONS)?; // 3e7
172 let f: f64 = lexical_core::parse_with_options::<_, JSON>(b"3.e7", &OPTIONS)?; // Errors!
173 ```
174
175 Due the high variability in the syntax of numbers in different programming and data languages, we provide 2 different APIs to simplify converting numbers with different syntax requirements.
176
177 - Number Format API (feature-gated via `format` or `power-of-two`).
178 <blockquote>This is a packed struct contained flags to specify compile-time syntax rules for number parsing or writing. This includes features such as the radix of the numeric string, digit separators, case-sensitive exponent characters, optional base prefixes/suffixes, and more.</blockquote>
179 - Options API.
180 <blockquote>This contains run-time rules for parsing and writing numbers. This includes exponent break points, rounding modes, the exponent and decimal point characters, and the string representation of NaN and Infinity.</blockquote>
181
182 A limited subset of functionality is documented in examples below, however, the complete specification can be found in the API reference documentation ([parse-float](https://docs.rs/lexical-parse-float/latest/lexical_parse_float/struct.Options.html), [parse-integer](https://docs.rs/lexical-parse-integer/latest/lexical_parse_integer/struct.Options.html), and [write-float](https://docs.rs/lexical-write-float/latest/lexical_write_float/struct.Options.html)).
183
184 ### Number Format API
185
186 The number format class provides numerous flags to specify number syntax when parsing or writing. When the `power-of-two` feature is enabled, additional flags are added:
187
188 - The radix for the significant digits (default `10`).
189 - The radix for the exponent base (default `10`).
190 - The radix for the exponent digits (default `10`).
191
192 When the `format` feature is enabled, numerous other syntax and digit separator flags are enabled, including:
193
194 - A digit separator character, to group digits for increased legibility.
195 - Whether leading, trailing, internal, and consecutive digit separators are allowed.
196 - Toggling required float components, such as digits before the decimal point.
197 - Toggling whether special floats are allowed or are case-sensitive.
198
199 Many pre-defined constants therefore exist to simplify common use-cases,
200 including:
201 - [`JSON`], [`XML`], [`TOML`], [`YAML`], [`SQLite`], and many more.
202 - [`Rust`], [`Python`], [`C#`], [`FORTRAN`], [`COBOL`] literals and strings, and many more.
203
204 [`JSON`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.JSON.html
205 [`XML`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.XML.html
206 [`TOML`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.TOML.html
207 [`YAML`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.YAML.html
208 [`SQLite`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.SQLITE.html
209 [`Rust`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.RUST_LITERAL.html
210 [`Python`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.PYTHON_LITERAL.html
211 [`C#`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.CSHARP_LITERAL.html
212 [`FORTRAN`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.FORTRAN_LITERAL.html
213 [`COBOL`]: https://docs.rs/lexical-core/latest/lexical_core/format/constant.COBOL_LITERAL.html
214
215 An example of building a custom number format is as follows:
216
217 ```rust
218 // this will panic if the format is invalid
219 const FORMAT: u128 = lexical_core::NumberFormatBuilder::new()
220 // Disable exponent notation.
221 .no_exponent_notation(true)
222 // Disable all special numbers, such as Nan and Inf.
223 .no_special(true)
224 .build_strict();
225 ```
226
227 ### Options API
228
229 The options API allows customizing number parsing and writing at run-time, such as specifying the maximum number of significant digits, exponent characters, and more.
230
231 An example of building a custom options struct is as follows:
232
233 ```rust
234 use std::num;
235
236 const OPTIONS: lexical_core::WriteFloatOptions = lexical_core::WriteFloatOptions::builder()
237 // Only write up to 5 significant digits, IE, `1.23456` becomes `1.2345`.
238 .max_significant_digits(num::NonZeroUsize::new(5))
239 // Never write less than 5 significant digits, `1.1` becomes `1.1000`.
240 .min_significant_digits(num::NonZeroUsize::new(5))
241 // Trim the trailing `.0` from integral float strings.
242 .trim_floats(true)
243 // Use a European-style decimal point.
244 .decimal_point(b',')
245 // Panic if we try to write NaN as a string.
246 .nan_string(None)
247 // Write infinity as "Infinity".
248 .inf_string(Some(b"Infinity"))
249 .build_strict();
250 ```
251
252 ## Documentation
253
254 Lexical's API reference can be found on [docs.rs](https://docs.rs/lexical), as can [lexical-core's](lexical-core). Detailed descriptions of the algorithms used can be found here:
255
256 - [Parsing Integers](https://github.com/Alexhuszagh/rust-lexical/blob/main/lexical-parse-integer/docs/Algorithm.md)
257 - [Parsing Floats](https://github.com/Alexhuszagh/rust-lexical/blob/main/lexical-parse-float/docs/Algorithm.md)
258 - [Writing Integers](https://github.com/Alexhuszagh/rust-lexical/blob/main/lexical-write-integer/docs/Algorithm.md)
259 - [Writing Floats](https://github.com/Alexhuszagh/rust-lexical/blob/main/lexical-write-float/docs/Algorithm.md)
260
261 In addition, descriptions of how lexical handles [digit separators](https://github.com/Alexhuszagh/rust-lexical/blob/main/docs/DigitSeparators.md) and implements [big-integer arithmetic](https://github.com/Alexhuszagh/rust-lexical/blob/main/lexical-parse-float/docs/BigInteger.md) are also documented.
262
263 ## Validation
264
265 **Float-Parsing**
266
267 Float parsing is difficult to do correctly, and major bugs have been found in implementations from [libstdc++'s strtod](https://www.exploringbinary.com/glibc-strtod-incorrectly-converts-2-to-the-negative-1075/) to [Python](https://bugs.python.org/issue7632). In order to validate the accuracy of the lexical, we employ the following external tests:
268
269 1. Hrvoje Abraham's [strtod](https://github.com/ahrvoje/numerics/tree/master/strtod) test cases.
270 2. Rust's [test-float-parse](https://github.com/rust-lang/rust/tree/64185f205dcbd8db255ad6674e43c63423f2369a/src/etc/test-float-parse) unittests.
271 3. Testbase's [stress tests](https://www.icir.org/vern/papers/testbase-report.pdf) for converting from decimal to binary.
272 4. Nigel Tao's [tests](https://github.com/nigeltao/parse-number-fxx-test-data) extracted from test suites for Freetype, Google's double-conversion library, IBM's IEEE-754R compliance test, as well as numerous other curated examples.
273 5. [Various](https://www.exploringbinary.com/glibc-strtod-incorrectly-converts-2-to-the-negative-1075/) [difficult](https://www.exploringbinary.com/how-glibc-strtod-works/) [cases](https://www.exploringbinary.com/how-strtod-works-and-sometimes-doesnt/) reported on blogs.
274
275 Lexical is extensively used in production, the same float parsing algorithm has been adopted by Golang's and Rust's standard libraries, and is unlikely to have correctness issues.
276
277 ## Metrics
278
279 Various benchmarks, binary sizes, and compile times are shown here. All the benchmarks can be found on [lexical-benchmarks](https://github.com/Alexhuszagh/lexical-benchmarks?tab=readme-ov-file#latest-results). All benchmarks used a black box to avoid optimizing out the result and leading to misleading metrics.
280
281 **Build Timings**
282
283 The compile-times when building with all numeric conversions enabled. For a more fine-tuned breakdown, see [build timings](https://github.com/Alexhuszagh/rust-lexical/blob/main/docs/BuildTimings.md).
284
285 ![Build Timings](https://raw.githubusercontent.com/Alexhuszagh/rust-lexical/main/assets/timings_all_posix.svg)
286
287 **Binary Size**
288
289 The binary sizes of stripped binaries compiled at optimization level "2". For a more fine-tuned breakdown, see [binary sizes](https://github.com/Alexhuszagh/rust-lexical/blob/main/docs/BinarySize.md).
290
291 ![Parse Stripped - Optimization Level "2"](https://raw.githubusercontent.com/Alexhuszagh/rust-lexical/main/assets/size_parse_stripped_opt2_posix.svg)
292 ![Write Stripped - Optimization Level "2"](https://raw.githubusercontent.com/Alexhuszagh/rust-lexical/main/assets/size_write_stripped_opt2_posix.svg)
293
294 ### Benchmarks — Parse Integer
295
296 **Random**
297
298 A benchmark on randomly-generated integers uniformly distributed over the entire range.
299
300 ![Uniform Random Data](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/json_random%20-%20parse%20int%20-%20core,lexical.png)
301
302 **Simple**
303
304 A benchmark on randomly-generated integers from 1-1000.
305
306 ![Simple Random Data](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/json_simple%20-%20parse%20int%20-%20core,lexical.png)
307
308 ### Benchmarks — Parse Float
309
310 **Real-World Datasets**
311
312 A benchmark on parsing floats from various real-world data sets, including Canada, Mesh, and astronomical data (earth).
313
314 ![Canada](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/canada%20-%20parse%20float%20-%20core,lexical.png)
315
316 ![Earth](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/earth%20-%20parse%20float%20-%20core,lexical.png)
317
318 ![Mesh](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/mesh%20-%20parse%20float%20-%20core,lexical.png)
319
320 **Random**
321
322 A benchmark on randomly-generated integers uniformly distributed over the entire range.
323
324 ![Random Big Integer](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/random_big_ints%20-%20parse%20float%20-%20core,lexical.png)
325
326 **Simple**
327
328 A benchmark on randomly-generated integers from 1-1000.
329
330 ![Random Simple](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/random_simple_int64%20-%20parse%20float%20-%20core,lexical.png)
331
332 ### Benchmarks — Write Integer
333
334 **Random**
335
336 A benchmark on randomly-generated integers uniformly distributed over the entire range.
337
338 ![Random Uniform](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/json_chain_random%20-%20write%20int%20-%20fmt,itoa,lexical.png)
339
340 **Simple**
341
342 ![Random Simple](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/json_simple%20-%20write%20int%20-%20fmt,itoa,lexical.png)
343
344 **Large**
345
346 ![Random Large](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/random_large%20-%20write%20int%20-%20fmt,itoa,lexical.png)
347
348 ### Benchmarks — Write Float
349
350 **Big Integer**
351
352 A benchmarks for values with a large integers.
353
354 ![Big Integers](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/random_big_ints%20-%20write%20float%20-%20dtoa,fmt,lexical,ryu.png)
355
356 **Simple 64-Bit Inteers**
357
358 ![Simple Int64](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/random_simple_int64%20-%20write%20float%20-%20dtoa,fmt,lexical,ryu.png)
359
360 **Random**
361
362 ![Random](https://github.com/Alexhuszagh/lexical-benchmarks/raw/main/results/latest/plot/json%20-%20write%20float%20-%20dtoa,fmt,lexical,ryu.png)
363
364 ## Safety
365
366 Due to the use of memory unsafe code in the library, we extensively fuzz our float writers and parsers. The fuzz harnesses may be found under [fuzz](https://github.com/Alexhuszagh/rust-lexical/tree/main/fuzz), and are run continuously. So far, we've parsed and written over 72 billion floats.
367
368 ## Platform Support
369
370 lexical-core is tested on a wide variety of platforms, including big and small-endian systems, to ensure portable code. Supported architectures include:
371 - x86_64 Linux, Windows, macOS, Android, iOS, FreeBSD, and NetBSD.
372 - x86 Linux, macOS, Android, iOS, and FreeBSD.
373 - aarch64 (ARM8v8-A) Linux, Android, and iOS.
374 - armv7 (ARMv7-A) Linux, Android, and iOS.
375 - arm (ARMv6) Linux, and Android.
376 - powerpc (PowerPC) Linux.
377 - powerpc64 (PPC64) Linux.
378 - powerpc64le (PPC64LE) Linux.
379 - s390x (IBM Z) Linux.
380
381 lexical-core should also work on a wide variety of other architectures and ISAs. If you have any issue compiling lexical-core on any architecture, please file a bug report.
382
383 ## Versioning and Version Support
384
385 **Version Support**
386
387 The currently supported versions are:
388 - v1.0.x
389
390 Due to security considerations, all other versions are not supported and security advisories exist for them.
391
392 **Rustc Compatibility**
393
394 - v1.0.x supports 1.63+, including stable, beta, and nightly.
395
396 Please report any errors compiling a supported `lexical` version on a compatible Rustc version.
397
398 **Versioning**
399
400 `lexical` uses [semantic versioning](https://semver.org/). Removing support for Rustc versions newer than the latest stable Debian or Ubuntu version is considered an incompatible API change, requiring a major version change.
401
402 ## Changelog
403
404 All changes are documented in [CHANGELOG](https://github.com/Alexhuszagh/rust-lexical/blob/main/CHANGELOG).
405
406 ## License
407
408 Lexical is dual licensed under the Apache 2.0 license as well as the MIT license. See the [LICENSE.md](LICENSE.md) file for full license details.
409
410 ## Contributing
411
412 Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in `lexical` by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. Contributing to the repository means abiding by the [code of conduct](https://github.com/Alexhuszagh/rust-lexical/blob/main/CODE_OF_CONDUCT.md).
413
414 For the process on how to contribute to `lexical`, see the [development](https://github.com/Alexhuszagh/rust-lexical/blob/main/docs/Development.md) quick-start guide.