{"id":19135084,"url":"https://github.com/moddedtechnic/lexical-core-0.7.4","last_synced_at":"2025-11-12T22:02:54.641Z","repository":{"id":128775891,"uuid":"559042199","full_name":"moddedTechnic/lexical-core-0.7.4","owner":"moddedTechnic","description":"UNOFFICIAL: this repo is a version of the described crate with some errors fixed from a reverse engineering challenge. Low-level, lexical conversion routines for use in a no_std context. This crate by default does not use the Rust standard library.","archived":false,"fork":false,"pushed_at":"2022-10-28T22:38:18.000Z","size":518,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-02-22T17:49:29.843Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/moddedTechnic.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-28T22:33:10.000Z","updated_at":"2022-10-28T22:35:15.000Z","dependencies_parsed_at":"2023-04-10T23:02:10.481Z","dependency_job_id":null,"html_url":"https://github.com/moddedTechnic/lexical-core-0.7.4","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/moddedTechnic/lexical-core-0.7.4","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moddedTechnic%2Flexical-core-0.7.4","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moddedTechnic%2Flexical-core-0.7.4/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moddedTechnic%2Flexical-core-0.7.4/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moddedTechnic%2Flexical-core-0.7.4/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/moddedTechnic","download_url":"https://codeload.github.com/moddedTechnic/lexical-core-0.7.4/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moddedTechnic%2Flexical-core-0.7.4/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284115871,"owners_count":26949957,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-12T02:00:06.336Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T06:29:05.901Z","updated_at":"2025-11-12T22:02:54.597Z","avatar_url":"https://github.com/moddedTechnic.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"lexical-core\n============\n\n# WARNING\n\nThis repo is an **unofficial** version of the below described crate with some errors fixed from a reverse engineering challenge.\nThe build and version labels have been removed from here to reflect this.\n\n---\n\nLow-level, lexical conversion routines for use in a `no_std` context. This crate by default does not use the Rust standard library.\n\n- [Getting Started](#getting-started)\n- [Features](#features)\n  - [Format](#format)\n- [Configuration](#configuration)\n- [Constants](#constants)\n- [Documentation](#documentation)\n- [Validation](#validation)\n- [Implementation Details](#implementation-details)\n  - [Float to String](#float-to-string)\n  - [String to Float](#string-to-float)\n  - [Arbitrary-Precision Arithmetic](#arbitrary-precision-arithmetic)\n  - [Algorithm Background and Comparison](#algorithm-background-and-comparison)\n- [Known Issues](#known-issues)\n- [Versioning and Version Support](#versioning-and-version-support)\n- [Changelog](#changelog)\n- [License](#license)\n- [Contributing](#contributing)\n\n# Getting Started\n\nlexical-core is a low-level API for number-to-string and string-to-number conversions, without requiring a system allocator. If you would like to use a convenient, high-level API, please look at [lexical](../lexical) instead.\n\nAdd lexical-core to your `Cargo.toml`:\n\n```toml\n[dependencies]\nlexical-core = \"^0.7.1\"\n```\n\nAnd an introduction through use:\n\n```rust\nextern crate lexical_core;\n\n// String to number using Rust slices.\n// The argument is the byte string parsed.\nlet f: f32 = lexical_core::parse(b\"3.5\").unwrap();   // 3.5\nlet i: i32 = lexical_core::parse(b\"15\").unwrap();    // 15\n\n// All lexical_core parsers are checked, they validate the\n// input data is entirely correct, and stop parsing when invalid data\n// is found, or upon numerical overflow.\nlet r = lexical_core::parse::\u003cu8\u003e(b\"256\"); // Err(ErrorCode::Overflow.into())\nlet r = lexical_core::parse::\u003cu8\u003e(b\"1a5\"); // Err(ErrorCode::InvalidDigit.into())\n\n// In order to extract and parse a number from a substring of the input\n// data, use `parse_partial`. These functions return the parsed value and \n// the number of processed digits, allowing you to extract and parse the \n// number in a single pass.\nlet r = lexical_core::parse_partial::\u003ci8\u003e(b\"3a5\"); // Ok((3, 1))\n\n// If an insufficiently long buffer is passed, the serializer will panic.\n// PANICS\nlet mut buf = [b'0'; 1];\n//let slc = lexical_core::write::\u003ci64\u003e(15, \u0026mut buf);\n\n// In order to guarantee the buffer is long enough, always ensure there\n// are at least `T::FORMATTED_SIZE` bytes, which requires the\n// `lexical_core::Number` trait to be in scope.\nuse lexical_core::Number;\nlet mut buf = [b'0'; f64::FORMATTED_SIZE];\nlet slc = lexical_core::write::\u003cf64\u003e(15.1, \u0026mut buf);\nassert_eq!(slc, b\"15.1\");\n\n// When the `radix` feature is enabled, for decimal floats, using\n// `T::FORMATTED_SIZE` may significantly overestimate the space\n// required to format the number. Therefore, the\n// `T::FORMATTED_SIZE_DECIMAL` constants allow you to get a much\n// tighter bound on the space required.\nlet mut buf = [b'0'; f64::FORMATTED_SIZE_DECIMAL];\nlet slc = lexical_core::write::\u003cf64\u003e(15.1, \u0026mut buf);\nassert_eq!(slc, b\"15.1\");\n```\n\n# Features\n\n- **correct** Use a correct string-to-float parser. \n    \u003cblockquote\u003eEnabled by default, and may be turned off by setting \u003ccode\u003edefault-features = false\u003c/code\u003e. If neither \u003ccode\u003ealgorithm_m\u003c/code\u003e nor \u003ccode\u003ebhcomp\u003c/code\u003e is enabled while \u003ccode\u003ecorrect\u003c/code\u003e is enabled, lexical uses the \u003ccode\u003ebigcomp\u003c/code\u003e algorithm.\u003c/blockquote\u003e\n- **trim_floats** Export floats without a fraction as an integer. \n    \u003cblockquote\u003eFor example, \u003ccode\u003e0.0f64\u003c/code\u003e will be serialized to \"0\" and not \"0.0\", and \u003ccode\u003e-0.0\u003c/code\u003e as \"0\" and not \"-0.0\".\u003c/blockquote\u003e\n- **radix** Allow conversions to and from non-decimal strings. \n    \u003cblockquote\u003eWith radix enabled, any radix from 2 to 36 (inclusive) is valid, otherwise, only 10 is valid.\u003c/blockquote\u003e\n- **format** Customize accepted inputs for number parsing.\n    \u003cblockquote\u003eWith format enabled, the number format is dictated through the \u003ccode\u003eNumberFormat\u003c/code\u003e bitflags, which allow you to toggle how to parse a string into a number. Various flags including enabling digit separators, requiring integer or fraction digits, and toggling special values.\u003c/blockquote\u003e\n- **rounding** Enable custom rounding for IEEE754 floats.\n    \u003cblockquote\u003eBy default, lexical uses round-nearest, tie-even for float rounding (recommended by IEE754).\u003c/blockquote\u003e\n- **ryu** Use dtolnay's [ryu](https://github.com/dtolnay/ryu/) library for float-to-string conversions.\n    \u003cblockquote\u003eEnabled by default, and may be turned off by setting \u003ccode\u003edefault-features = false\u003c/code\u003e. Ryu is ~2x as fast as other float formatters.\u003c/blockquote\u003e\n\n\n## Format\n\nEvery 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:\n\n```rust\nextern crate lexical_core;\n\nuse lexical_core::*;\n\n// Valid in Rust strings.\n// Not valid in JSON.\nlet f: f64 = parse(b\"3.e7\").unwrap();                       // 3e7\n\n// Let's only accept JSON floats.\nlet format = NumberFormat::JSON;\nlet f: f64 = parse_format(b\"3.0e7\", format).unwrap();       // 3e7\nlet f: f64 = parse_format(b\"3.e7\", format).unwrap();        // Panics!\n\n// We can also allow digit separators, for example.\n// OCaml, a programming language that inspired Rust,\n// accepts digit separators pretty much anywhere.\nlet format = NumberFormat::OCAML_STRING;\nlet f: f64 = parse(b\"3_4.__0_1\").unwrap();                  // Panics!\nlet f: f64 = parse_format(b\"3_4.__0_1\", format).unwrap();   // 34.01\n```\n\nThe parsing specification is defined by `NumberFormat`, which provides pre-defined constants for over 40 programming and data languages. However, it also allows you to create your own specification, to dictate parsing.\n\n```rust\nextern crate lexical_core;\n\nuse lexical_core::*;\n\n// Let's use the standard, Rust grammar.\nlet format = NumberFormat::standard().unwrap();\n\n// Let's use a permissive grammar, one that allows anything besides\n// digit separators.\nlet format = NumberFormat::permissive().unwrap();\n\n// Let's ignore digit separators and have an otherwise permissive grammar.\nlet format = NumberFormat::ignore(b'_').unwrap();\n\n// Create our own grammar.\n// A NumberFormat is compiled from options into binary flags, each\n// taking 1-bit, allowing high-performance, customizable parsing\n// once they're compiled. Each flag will be explained while defining it.\n\n// The '_' character will be used as a digit separator.\nlet digit_separator = b'_';\n\n// Require digits in the integer component of a float.\n// `0.1` is valid, but `.1` is not.\nlet required_integer_digits = false;\n\n// Require digits in the fraction component of a float.\n// `1.0` is valid, but `1.` and `1` are not.\nlet required_fraction_digits = false;\n\n// Require digits in the exponent component of a float.\n// `1.0` and `1.0e7` is valid, but `1.0e` is not.\nlet required_exponent_digits = false;\n\n// Do not allow a positive sign before the mantissa.\n// `1.0` and `-1.0` are valid, but `+1.0` is not.\nlet no_positive_mantissa_sign = false;\n\n// Require a sign before the mantissa.\n// `+1.0` and `-1.0` are valid, but `1.0` is not.\nlet required_mantissa_sign = false;\n\n// Do not allow the use of exponents.\n// `300.0` is valid, but `3.0e2` is not.\nlet no_exponent_notation = false;\n\n// Do not allow a positive sign before the exponent.\n// `3.0e2` and 3.0e-2` are valid, but `3.0e+2` is not.\nlet no_positive_exponent_sign = false;\n\n// Require a sign before the exponent.\n// `3.0e+2` and `3.0e-2` are valid, but `3.0e2` is not.\nlet required_exponent_sign = false;\n\n// Do not allow an exponent without fraction digits.\n// `3.0e7` is valid, but `3e7` and `3.e7` are not.\nlet no_exponent_without_fraction = false;\n\n// Do not allow special values.\n// `1.0` is valid, but `NaN` and `inf` are not.\nlet no_special = false;\n\n// Use case-sensitive matching when parsing special values.\n// `NaN` is valid, but `nan` and `NAN` are not.\nlet case_sensitive_special = false;\n\n// Allow digit separators between digits in the integer component.\n// `3_4.01` is valid, but `_34.01`, `34_.01` and `34.0_1` are not.\nlet integer_internal_digit_separator = false;\n\n// Allow digit separators between digits in the fraction component.\n// `34.0_1` is valid, but `34._01`, `34.01_` and `3_4.01` are not.\nlet fraction_internal_digit_separator = false;\n\n// Allow digit separators between digits in the exponent component.\n// `1.0e6_7` is valid, but `1.0e_67`, `1.0e67_` and `1_2.0e67` are not.\nlet exponent_internal_digit_separator = false;\n\n// Allow digit separators before any digits in the integer component.\n// These digit separators may occur before or after the sign, as long\n// as they occur before any digits.\n// `_34.01` is valid, but `3_4.01`, `34_.01` and `34._01` are not.\nlet integer_leading_digit_separator = false;\n\n// Allow digit separators before any digits in the fraction component.\n// `34._01` is valid, but `34.0_1`, `34.01_` and `_34.01` are not.\nlet fraction_leading_digit_separator = false;\n\n// Allow digit separators before any digits in the exponent component.\n// These digit separators may occur before or after the sign, as long\n// as they occur before any digits.\n// `1.0e_67` is valid, but `1.0e6_7`, `1.0e67_` and `_1.0e67` are not.\nlet exponent_leading_digit_separator = false;\n\n// Allow digit separators after any digits in the integer component.\n// If `required_integer_digits` is not set, `_.01` is valid.\n// `34_.01` is valid, but `3_4.01`, `_34.01` and `34.01_` are not.\nlet integer_trailing_digit_separator = false;\n\n// Allow digit separators after any digits in the fraction component.\n// If `required_fraction_digits` is not set, `1._` is valid.\n// `34.01_` is valid, but `34.0_1`, `34._01` and `34_.01` are not.\nlet fraction_trailing_digit_separator = false;\n\n// Allow digit separators after any digits in the exponent component.\n// If `required_exponent_digits` is not set, `1.0e_` is valid.\n// `1.0e67_` is valid, but `1.0e6_7`, `1.0e_67` and `1.0_e67` are not.\nlet exponent_trailing_digit_separator = false;\n\n// Allow consecutive separators in the integer component.\n// This requires another integer digit separator flag to be set.\n// For example, if `integer_internal_digit_separator` and this flag are set,\n// `3__4.01` is valid, but `__34.01`, `34__.01` and `34.0__1` are not.\nlet integer_consecutive_digit_separator = false;\n\n// Allow consecutive separators in the fraction component.\n// This requires another fraction digit separator flag to be set.\n// For example, if `fraction_internal_digit_separator` and this flag are set,\n// `34.0__1` is valid, but `34.__01`, `34.01__` and `3__4.01` are not.\nlet fraction_consecutive_digit_separator = false;\n\n// Allow consecutive separators in the exponent component.\n// This requires another exponent digit separator flag to be set.\n// For example, if `exponent_internal_digit_separator` and this flag are set,\n// `1.0e6__7` is valid, but `1.0e__67`, `1.0e67__` and `1__2.0e67` are not.\nlet exponent_consecutive_digit_separator = false;\n\n// Allow digit separators in special values.\n// If set, allow digit separators in special values will be ignored.\n// `N_a_N__` is valid, but `i_n_f_e` is not.\nlet special_digit_separator = false;\n\n// Compile the grammar.\nlet format = NumberFormat::compile(\n    digit_separator,\n    required_integer_digits,\n    required_fraction_digits,\n    required_exponent_digits,\n    no_positive_mantissa_sign,\n    required_mantissa_sign,\n    no_exponent_notation,\n    no_positive_exponent_sign,\n    required_exponent_sign,\n    no_exponent_without_fraction,\n    no_special,\n    case_sensitive_special,\n    integer_internal_digit_separator,\n    fraction_internal_digit_separator,\n    exponent_internal_digit_separator,\n    integer_leading_digit_separator,\n    fraction_leading_digit_separator,\n    exponent_leading_digit_separator,\n    integer_trailing_digit_separator,\n    fraction_trailing_digit_separator,\n    exponent_trailing_digit_separator,\n    integer_consecutive_digit_separator,\n    fraction_consecutive_digit_separator,\n    exponent_consecutive_digit_separator,\n    special_digit_separator\n).unwrap();\n```\n\n# Configuration\n\nLexical-core also includes configuration options that allow you to configure float processing and formatting. These are provided as getters and setters, so lexical-core can validate the input.\n\n- **NaN**\n    - `get_nan_string`\n    - `set_nan_string`\n    \u003cblockquote\u003eThe representation of Not a Number (NaN) as a string (default \u003ccode\u003eb\"NaN\"\u003c/code\u003e). For float parsing, lexical-core uses case-insensitive comparisons. This string \u003cb\u003emust\u003c/b\u003e start with an \u003ccode\u003e'N'\u003c/code\u003e or \u003ccode\u003e'n'\u003c/code\u003e.\u003c/blockquote\u003e\n- **Short Infinity**\n    - `get_inf_string`\n    - `set_inf_string`\n    \u003cblockquote\u003eThe short, default representation of infinity as a string (default \u003ccode\u003eb\"inf\"\u003c/code\u003e). For float parsing, lexical-core uses case-insensitive comparisons. This string **must** start with an \u003ccode\u003e'I'\u003c/code\u003e or \u003ccode\u003e'i'\u003c/code\u003e.\u003c/blockquote\u003e\n- **Long Infinity**\n    - `get_infinity_string`\n    - `set_infinity_string`\n    \u003cblockquote\u003eThe long, backup representation of infinity as a string (default \u003ccode\u003eb\"infinity\"\u003c/code\u003e). The long infinity must be at least as long as the short infinity, and will only be used during float parsing (and is case-insensitive). This string **must** start with an \u003ccode\u003e'I'\u003c/code\u003e or \u003ccode\u003e'i'\u003c/code\u003e.\u003c/blockquote\u003e\n- **Exponent Default Character**\n    - `get_exponent_default_char`\n    - `set_exponent_default_char`\n    \u003cblockquote\u003eThe default character designating the exponent component of a float (default \u003ccode\u003eb'e'\u003c/code\u003e) for strings with a radix less than 15 (including decimal strings). For float parsing, lexical-core uses case-insensitive comparisons. This value should be not be in character set \u003ccode\u003e[0-9a-eA-E.+\\-]\u003c/code\u003e.\u003c/blockquote\u003e\n- **Exponent Backup Character** (radix only) \n    - `get_exponent_backup_char`\n    - `set_exponent_backup_char`\n    \u003cblockquote\u003eThe backup character designating the exponent component of a float (default \u003ccode\u003eb'^'\u003c/code\u003e) for strings with a radix greater than or equal to 15. This value should be not be in character set \u003ccode\u003e[0-9a-zA-Z.+\\-]\u003c/code\u003e.\u003c/blockquote\u003e\n- **Float Rounding** (rounding only)\n    - `get_float_rounding`\n    - `set_float_rounding`\n    \u003cblockquote\u003eThe IEEE754 float-rounding scheme to be used during float parsing. In almost every case, this should be set to \u003ccode\u003eRoundingKind::NearestTieEven\u003c/code\u003e.\u003c/blockquote\u003e\n\n# Constants\n\nLexical-core also includes a few constants to simplify interfacing with number-to-string code, and are implemented for the `lexical_core::Number` trait, which is required by `ToLexical`. \n\n- **FORMATTED_SIZE** The maximum number of bytes a formatter may write.\n    \u003cblockquote\u003eFor example, \u003ccode\u003elexical_core::write_radix::\u0026lt;i32\u0026gt;\u003c/code\u003e may write up to \u003ccode\u003ei32::FORMATTED_SIZE\u003c/code\u003e characters. This constant may significantly overestimate the number of characters required for decimal strings when the radix feature is enabled.\u003c/blockquote\u003e\n- **FORMATTED_SIZE_DECIMAL** The maximum number of bytes a formatter may write in decimal (base 10).\n    \u003cblockquote\u003eFor example, \u003ccode\u003elexical_core::write::\u0026lt;i32\u0026gt;\u003c/code\u003e may write up to \u003ccode\u003ei32::FORMATTED_SIZE_DECIMAL\u003c/code\u003e characters.\u003c/blockquote\u003e\n\nThese are provided as Rust constants so they may be used as the size element in arrays.\n\n# Documentation\n\nLexical-core's documentation can be found on [docs.rs](https://docs.rs/lexical-core).\n\n# Validation\n\nFloat 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:\n\n1. Hrvoje Abraham's [strtod](https://github.com/ahrvoje/numerics/tree/master/strtod) test cases.\n2. Rust's [test-float-parse](https://github.com/rust-lang/rust/tree/64185f205dcbd8db255ad6674e43c63423f2369a/src/etc/test-float-parse) unittests.\n3. Testbase's [stress tests](https://www.icir.org/vern/papers/testbase-report.pdf) for converting from decimal to binary.\n4. [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.\n\nAlthough lexical may contain bugs leading to rounding error, it is tested against a comprehensive suite of random-data and near-halfway representations, and should be fast and correct for the vast majority of use-cases.\n\n# Implementation Details\n\n## Float to String\n\nFor more information on the Grisu2 and Grisu3 algorithms, see [Printing Floating-Point Numbers Quickly and Accurately with Integers](https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf).\n\nFor more information on the Ryu algorithm, see [Ryū: fast float-to-string conversion](https://dl.acm.org/citation.cfm?id=3192369).\n\n## String to Float\n\nIn order to implement an efficient parser in Rust, lexical uses the following steps:\n\n1. We ignore the sign until the end, and merely toggle the sign bit after creating a correct representation of the positive float.\n2. We handle special floats, such as \"NaN\", \"inf\", \"Infinity\". If we do not have a special float, we continue to the next step.\n3. We parse up to 64-bits from the string for the mantissa, ignoring any trailing digits, and parse the exponent (if present) as a signed 32-bit integer. If the exponent overflows or underflows, we set the value to i32::max_value() or i32::min_value(), respectively.\n4. **Fast Path** We then try to create an exact representation of a native binary float from parsed mantissa and exponent. If both can be exactly represented, we multiply the two to create an exact representation, since IEEE754 floats mandate the use of guard digits to minimizing rounding error. If either component cannot be exactly represented as the native float, we continue to the next step.\n5. **Moderate Path** We create an approximate, extended, 80-bit float type (64-bits for the mantissa, 16-bits for the exponent) from both components, and multiplies them together. This minimizes the rounding error, through guard digits. We then estimate the error from the parsing and multiplication steps, and if the float +/- the error differs significantly from b+h, we return the correct representation (b or b+u). If we cannot unambiguously determine the correct floating-point representation, we continue to the next step.\n6. **Fallback Moderate Path** Next, we create a 128-bit representation of the numerator and denominator for b+h, to disambiguate b from b+u by comparing the actual digits in the input to theoretical digits generated from b+h. This is accurate for ~36 significant digits from a 128-bit approximation with decimal float strings. If the input is less than or equal to 36 digits, we return the value from this step. Otherwise, we continue to the next step.\n7. **Slow Path** We use arbitrary-precision arithmetic to disambiguate the correct representation without any rounding error. We create an exact representation of the input digits as a big integer, to determine how to round the top 53 bits for the mantissa. If there is a fraction or a negative exponent, we create a representation of the significant digits for `b+h` and scale the input digits by the binary exponent in `b+h`, and scale the significant digits in `b+h` by the decimal exponent, and compare the two to determine if we need to round up or down.\n\nSince arbitrary-precision arithmetic is slow and scales poorly for decimal strings with many digits or exponents of high magnitude, lexical also supports a lossy algorithm, which returns the result from the moderate path. The result from the lossy parser should be accurate to within 1 ULP.\n\n## Arbitrary-Precision Arithmetic\n\nLexical uses arbitrary-precision arithmetic to exactly represent strings between two floating-point representations, and is highly optimized for performance. The following section is a comparison of different algorithms to determine the correct float representation. The arbitrary-precision arithmetic logic is not dependent on memory allocation: it only uses the heap when the `radix` feature is enabled.\n\n## Algorithm Background and Comparison\n\nFor close-to-halfway representations of a decimal string `s`, where `s` is close between two representations, `b` and the next float `b+u`, arbitrary-precision arithmetic is used to determine the correct representation. This means `s` is close to `b+h`, where `h` is the halfway point between `b` and `b+u`.\n\nFor the following example, we will use the following values for our test case: \n\n* `s = 2.4703282292062327208828439643411068618252990130716238221279284125033775363510437593264991818081799618989828234772285886546332835517796989819938739800539093906315035659515570226392290858392449105184435931802849936536152500319370457678249219365623669863658480757001585769269903706311928279558551332927834338409351978015531246597263579574622766465272827220056374006485499977096599470454020828166226237857393450736339007967761930577506740176324673600968951340535537458516661134223766678604162159680461914467291840300530057530849048765391711386591646239524912623653881879636239373280423891018672348497668235089863388587925628302755995657524455507255189313690836254779186948667994968324049705821028513185451396213837722826145437693412532098591327667236328125001e-324`\n* `b = 0.0`\n* `b+h = 2.4703282292062327208828439643411068618252990130716238221279284125033775363510437593264991818081799618989828234772285886546332835517796989819938739800539093906315035659515570226392290858392449105184435931802849936536152500319370457678249219365623669863658480757001585769269903706311928279558551332927834338409351978015531246597263579574622766465272827220056374006485499977096599470454020828166226237857393450736339007967761930577506740176324673600968951340535537458516661134223766678604162159680461914467291840300530057530849048765391711386591646239524912623653881879636239373280423891018672348497668235089863388587925628302755995657524455507255189313690836254779186948667994968324049705821028513185451396213837722826145437693412532098591327667236328125e-324`\n* `b+u = 5e-324`\n\n**Algorithm M**\n\nAlgorithm M represents the significant digits of a float as a fraction of arbitrary-precision integers (a more in-depth description can be found [here](https://www.exploringbinary.com/correct-decimal-to-floating-point-using-big-integers/)). For example, 1.23 would be 123/100, while 314.159 would be 314159/1000. We then scale the numerator and denominator by powers of 2 until the quotient is in the range `[2^52, 2^53)`, generating the correct significant digits of the mantissa. \n\nA naive implementation, in Python, is as follows:\n\n```python\ndef algorithm_m(num, b):\n    # Ensure numerator \u003e= 2**52\n    bits = int(math.ceil(math.log2(num)))\n    if bits \u003c= 53:\n        num \u003c\u003c= 53\n        b -= 53\n\n    # Track number of steps required (optional).\n    steps = 0\n    while True:\n        steps += 1\n        c = num//b\n        if c \u003c 2**52:\n            b //= 2\n        elif c \u003e= 2**53:\n            b *= 2\n        else:\n            break\n\n    return (num, b, steps-1)\n```\n\n**bigcomp**\n\nBigcomp is the canonical string-to-float parser, which creates an exact representation of `b+h` as a big integer, and compares the theoretical digits from `b+h` scaled into the range `[1, 10)` by a power of 10 to the actual digits in the input string (a more in-depth description can be found [here](https://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/)). A maximum of 768 digits need to be compared to determine the correct representation, and the size of the big integers in the ratio does not depend on the number of digits in the input string.\n\nBigcomp is used as a fallback algorithm for lexical-core when the radix feature is enabled, since the radix-representation of a binary float may never terminate if the radix is not divisible by 2. Since bigcomp uses constant memory, it is used as the default algorithm if more than `2^15` digits are passed and the representation is potentially non-terminating.\n\n**bhcomp**\n\nBhcomp is a simple, performant algorithm that compared the significant digits to the theoretical significant digits for `b+h`. Simply, the significant digits from the string are parsed, creating a ratio. A ratio is generated for `b+h`, and these two ratios are scaled using the binary and radix exponents.\n\nFor example, \"2.470328e-324\" produces a ratio of `2470328/10^329`, while `b+h` produces a binary ratio of `1/2^1075`. We're looking to compare these ratios, so we need to scale them using common factors. Here, we convert this to `(2470328*5^329*2^1075)/10^329` and `(1*5^329*2^1075)/2^1075`, which converts to `2470328*2^746` and `1*5^329`.\n\nOur significant digits (real_digits) and `b+h` (bh_digits) therefore start like:\n```\nreal_digits = 91438982...\nbh_digits   = 91438991...\n```\n\nSince our real digits are below the theoretical halfway point, we know we need to round-down, meaning our literal value is `b`, or `0.0`. This approach allows us to calculate whether we need to round-up or down with a single comparison step, without any native divisions required. This is the default algorithm lexical-core uses.\n\n**Other Optimizations**\n\n1. We remove powers of 2 during exponentiation in bhcomp.\n2. We limit the number of parsed digits to the theoretical max number of digits produced by `b+h` (768 for decimal strings), and merely compare any trailing digits to '0'. This provides an upper-bound on the computation cost.\n3. We use fast exponentiation and multiplication algorithms to scale the significant digits for comparison.\n4. For the fallback bigcomp algorithm, we use a division algorithm optimized for the generation of a single digit from a given radix, by setting the leading bit in the denominator 4 below the most-significant bit (in decimal strings). This requires only 1 native division per digit generated.\n4. The individual \"limbs\" of the big integers are optimized to the architecture we compile on, for example, u32 on x86 and u64 on x86-64, minimizing the number of native operations required. Currently, 64-bit limbs are used on target architectures `aarch64`, `powerpc64`, `mips64`, and `x86_64`.\n\n# Known Issues\n\nOn the ARMVv6 architecture, the stable exponentiation for the fast, incorrect float parser is not fully stable. For example, `1e-300` is correct, while `5e-324` rounds to `0`, leading to \"5e-324\" being incorrectly parsed as `0`. This does not affect the default, correct float parser, nor ARMVv7 or ARMVv8 (aarch64) architectures. This bug can compound errors in the incorrect parser (feature-gated by disabling the `correct` feature`). It is not known if this bug is an artifact of Qemu emulation of ARMv6, or is actually representative the hardware.\n\nVersions of lexical-core prior to 0.4.3 could round parsed floating-point numbers with an error of up to 1 ULP. This occurred for strings with 16 or more digits and a trailing 0 in the fraction, the `b+h` comparison in the slow-path algorithm incorrectly scales the the theoretical digits due to an over-calculated real exponent. This affects a very small percentage of inputs, however, it is recommended to update immediately.\n\n# Versioning and Version Support\n\n**Version Support**\n\nThe currently supported versions are:\n- v0.7.x\n- v0.6.x (Maintenace)\n\n**Rustc Compatibility**\n\nv0.7.x supports 1.37+, including stable, beta, and nightly.\nv0.6.x supports Rustc 1.24+, including stable, beta, and nightly.\n\nPlease report any errors compiling a supported lexical-core version on a compatible Rustc version.\n\n**Versioning**\n\nLexical-core uses [semantic versioning](https://semver.org/). Removing support for older Rustc versions is considered an incompatible API change, requiring a major version change.\n\n# Changelog\n\nAll changes since 0.4.1 are documented in [CHANGELOG](CHANGELOG).\n\n# License\n\nLexical-core is dual licensed under the Apache 2.0 license as well as the MIT license. See the LICENCE-MIT and the LICENCE-APACHE files for the licenses.\n\nLexical-core also ports some code from [rust](https://github.com/rust-lang/rust) (for backwards compatibility), [V8](https://github.com/v8/v8), [libgo](https://golang.org/src) and [fpconv](https://github.com/night-shift/fpconv), and therefore might be subject to the terms of a 3-clause BSD license or BSD-like license.\n\n# Contributing\n\nUnless 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoddedtechnic%2Flexical-core-0.7.4","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmoddedtechnic%2Flexical-core-0.7.4","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoddedtechnic%2Flexical-core-0.7.4/lists"}