Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rust-lexical

> DevOps
Open source

Fast numeric to- and from-string conversion routines.

361 stars0 likes3 views
WebsiteGitHub

About

Fast numeric to- and from-string conversion routines.

lexical

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.

Similar Projects

If you want a minimal, performant float parser, recent versions of the Rust standard library should be sufficient. For high-performance integer formatters, look at itoa. The 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:

  • itoa
  • dtoa
  • ryu
  • Rust core library

Table of Contents

  • Getting Started
  • Partial/Complete Parsers
  • no_std
  • Features
  • Customization
    • Number Format API
    • Options API
  • Documentation
  • Validation
  • Metrics
  • Safety
  • Platform Support
  • Versioning and Version Support
  • Changelog
  • License
  • Contributing

Getting Started

Add lexical to your Cargo.toml:

toml
[dependencies]
lexical-core = "^1.0"

And get started using lexical:

rust
// Number to string
use lexical_core::BUFFER_SIZE;
let mut buffer = [b'0'; BUFFER_SIZE];
lexical_core::write(3.0, &mut buffer);   // "3.0", always has a fraction suffix,
lexical_core::write(3, &mut buffer);     // "3"

// String to number.
let i: i32 = lexical_core::parse("3")?;      // Ok(3), auto-type deduction.
let f: f32 = lexical_core::parse("3.5")?;    // Ok(3.5)
let d: f64 = lexical_core::parse("3.5")?;    // Ok(3.5), error checking parse.
let d: f64 = lexical_core::parse("3a")?;     // Err(Error(_)), failed to parse.

In order to use lexical in generic code, the trait bounds FromLexical (for parse) and ToLexical (for to_string) are provided.

rust
/// Multiply a value in a string by multiplier, and serialize to string.
fn mul_2(value: &str, multiplier: T)
    -> Result
where
    T: lexical_core::ToLexical + lexical_core::FromLexical,
{
    let value: T = lexical_core::parse(value.as_bytes())?;
    let mut buffer = [b'0'; lexical_core::BUFFER_SIZE];
    let bytes = lexical_core::write(value * multiplier, &mut buffer);
    Ok(String::from_utf8(bytes).unwrap())
}

Partial/Complete Parsers

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.

Complete Parsers

rust
// This will return Err(Error::InvalidDigit(3)), indicating
// the first invalid character occurred at the index 3 in the input
// string (the space character).
let x: i32 = lexical_core::parse(b"123 456")?;

Partial Parsers

rust
// This will return Ok((123, 3)), indicating that 3 digits were successfully
// parsed, and that the returned value is `123`.
let (x, count): (i32, usize) = lexical_core::parse_partial(b"123 456")?;

no_std

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:

[no_std]:

toml
[dependencies.lexical-core]
version = "1.0.0"
default-features = false
# Can select only desired parsing/writing features.
features = ["write-integers", "write-floats", "parse-integers", "parse-floats"]

And get started using lexical-core:

…

Features

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.

  • parse-floats:   Enable string-to-float conversions.
  • parse-integers:   Enable string-to-integer conversions.
  • write-floats:   Enable float-to-string conversions.
  • write-integers:   Enable integer-to-string conversions.

Lexical is highly customizable, and contains numerous other optional features:

  • std:   Enable use of the Rust standard library (enabled by default).
  • power-of-two:   Enable conversions to and from non-decimal strings.

With power_of_two enabled, the radixes {2, 4, 8, 10, 16, and 32} are valid, otherwise, only 10 is valid. This enables common conversions to/from hexadecimal integers/floats, without requiring large pre-computed tables for other radixes.

  • radix:   Allow conversions to and from non-decimal strings.

With radix enabled, any radix from 2 to 36 (inclusive) is valid, otherwise, only 10 is valid.

  • format:   Customize acceptable number formats for number parsing and writing.

With format enabled, the number format is dictated through bitflags and masks packed into a u128. 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.

  • compact:   Optimize for binary size at the expense of performance.

This minimizes the use of pre-computed tables, producing significantly smaller binaries.

  • f16:   Add support for numeric conversions to-and-from 16-bit floats.

Adds f16, a half-precision IEEE-754 floating-point type, and bf16, 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 f32.

To ensure memory safety, we extensively fuzz the all numeric conversion routines. See the Safety section below for more information.

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.

Customization

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.

⚠ 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.

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:

rust
// Valid in Rust strings.
// Not valid in JSON.
let f: f64 = lexical_core::parse(b"3.e7")?;  // 3e7

// Let's only accept JSON floats.
const JSON: u128 = lexical_core::format::JSON;
const OPTIONS: ParseFloatOptions = ParseFloatOptions::new();
let f: f64 = lexical_core::parse_with_options::(b"3.0e7", &OPTIONS)?; // 3e7
let f: f64 = lexical_core::parse_with_options::(b"3.e7", &OPTIONS)?;  // Errors!

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.

  • Number Format API (feature-gated via format or power-of-two).

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.

  • Options API.

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.

A limited subset of functionality is documented in examples below, however, the complete specification can be found in the API reference documentation (parse-float, parse-integer, and write-float).

Number Format API

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:

  • The radix for the significant digits (default 10).
  • The radix for the exponent base (default 10).
  • The radix for the exponent digits (default 10).

When the format feature is enabled, numerous other syntax and digit separator flags are enabled, including:

  • A digit separator character, to group digits for increased legibility.
  • Whether leading, trailing, internal, and consecutive digit separators are allowed.
  • Toggling required float components, such as digits before the decimal point.
  • Toggling whether special floats are allowed or are case-sensitive.

Many pre-defined constants therefore exist to simplify common use-cases, including:

  • JSON, XML, TOML, YAML, SQLite, and many more.
  • Rust, Python, C#, FORTRAN, COBOL literals and strings, and many more.

An example of building a custom number format is as follows:

rust
// this will panic if the format is invalid
const FORMAT: u128 = lexical_core::NumberFormatBuilder::new()
    // Disable exponent notation.
    .no_exponent_notation(true)
    // Disable all special numbers, such as Nan and Inf.
    .no_special(true)
    .build_strict();

Options API

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.

An example of building a custom options struct is as follows:

…

Documentation

Lexical's API reference can be found on [docs.rs](https://docs.rs/lexic

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustencodingfloating-pointno-stdparsing

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理