summaryrefslogtreecommitdiffstats
path: root/vendor/btoi
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 12:41:35 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 12:41:35 +0000
commit7e5d7eea9c580ef4b41a765bde624af431942b96 (patch)
tree2c0d9ca12878fc4525650aa4e54d77a81a07cc09 /vendor/btoi
parentAdding debian version 1.70.0+dfsg1-9. (diff)
downloadrustc-7e5d7eea9c580ef4b41a765bde624af431942b96.tar.xz
rustc-7e5d7eea9c580ef4b41a765bde624af431942b96.zip
Merging upstream version 1.70.0+dfsg2.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/btoi')
-rw-r--r--vendor/btoi/.cargo-checksum.json1
-rw-r--r--vendor/btoi/Cargo.toml44
-rw-r--r--vendor/btoi/LICENSE-APACHE201
-rw-r--r--vendor/btoi/LICENSE-MIT25
-rw-r--r--vendor/btoi/README.md62
-rw-r--r--vendor/btoi/benches/benches.rs85
-rw-r--r--vendor/btoi/rustfmt.toml2
-rw-r--r--vendor/btoi/src/lib.rs659
8 files changed, 1079 insertions, 0 deletions
diff --git a/vendor/btoi/.cargo-checksum.json b/vendor/btoi/.cargo-checksum.json
new file mode 100644
index 000000000..4df8046bc
--- /dev/null
+++ b/vendor/btoi/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{"Cargo.toml":"503aae9fe0d1f42c76d4c23078488540bc81d3903242b28a617cc966ee202a9a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c189dcc7339b95c2731e2bdfb5dcda6afe8b48ff5c983cdbb38825eacdec9f1b","README.md":"80304128592c0ca44e6d7ff256ba736f24809f3db36d38352297564f185eb515","benches/benches.rs":"3da1c994926cf09b91580889d6c2a116f754ab00e6adf34134304de9c88279e5","rustfmt.toml":"aa60e6f3213eeeec0880d940c3aeafdfd8815a7fc230780e6a9ac3dc18e1bfa8","src/lib.rs":"ddb3189335a585829cb206b64a6edba1e2812ea3811d42494de1060472f16c42"},"package":"9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad"} \ No newline at end of file
diff --git a/vendor/btoi/Cargo.toml b/vendor/btoi/Cargo.toml
new file mode 100644
index 000000000..b461b83ef
--- /dev/null
+++ b/vendor/btoi/Cargo.toml
@@ -0,0 +1,44 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+name = "btoi"
+version = "0.4.3"
+authors = ["Niklas Fiekas <niklas.fiekas@backscattering.de>"]
+description = "Parse integers directly from ASCII byte slices"
+readme = "README.md"
+keywords = [
+ "conversion",
+ "integer",
+ "atoi",
+ "no_std",
+]
+categories = ["parsing"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/niklasf/rust-btoi"
+
+[[bench]]
+name = "benches"
+harness = false
+
+[dependencies.num-traits]
+version = "0.2"
+default-features = false
+
+[dev-dependencies.bencher]
+version = "0.1"
+
+[dev-dependencies.quickcheck]
+version = "1"
+
+[features]
+default = ["std"]
+std = ["num-traits/std"]
diff --git a/vendor/btoi/LICENSE-APACHE b/vendor/btoi/LICENSE-APACHE
new file mode 100644
index 000000000..16fe87b06
--- /dev/null
+++ b/vendor/btoi/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/vendor/btoi/LICENSE-MIT b/vendor/btoi/LICENSE-MIT
new file mode 100644
index 000000000..e16573e9e
--- /dev/null
+++ b/vendor/btoi/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2017-2023 Niklas Fiekas
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/vendor/btoi/README.md b/vendor/btoi/README.md
new file mode 100644
index 000000000..be6932fea
--- /dev/null
+++ b/vendor/btoi/README.md
@@ -0,0 +1,62 @@
+btoi
+====
+
+Parse integers from ASCII byte slices.
+
+[![crates.io](https://img.shields.io/crates/v/btoi.svg)](https://crates.io/crates/btoi)
+[![docs.rs](https://docs.rs/btoi/badge.svg)](https://docs.rs/btoi)
+
+Introduction
+------------
+
+Provides functions similar to [`from_str_radix`](https://doc.rust-lang.org/std/primitive.u32.html#method.from_str_radix),
+but is faster when parsing directly from byte slices instead of strings.
+
+Supports `#![no_std]`.
+
+```rust
+use btoi::btoi;
+
+assert_eq!(Ok(42), btoi(b"42"));
+assert_eq!(Ok(-1000), btoi(b"-1000"));
+```
+
+Documentation
+-------------
+
+[Read the documentation](https://docs.rs/btoi)
+
+Changelog
+---------
+
+* 0.4.3
+ - Use `#[track_caller]`.
+* 0.4.2
+ - No longer `!#[deny(warnings)]`, which is is a forwards compability hazard
+ in libraries.
+ - Explicit `!#[forbid(unsafe_code)]`.
+* 0.4.1
+ - `-` was parsed as zero, but should have errored. Thanks @wayslog.
+* 0.4.0
+ - Change type of radix to `u32` (from `u8`) to mirror the standard library.
+ - No need to `#[inline]` generic functions.
+* 0.3.0
+ - New default feature `std`. Disable for `#![no_std]` support.
+ - Mark functions as `#[inline]`.
+* 0.2.0
+ - No longer reexport num-traits.
+* 0.1.3
+ - Update to num-traits 0.2 (semver compatible).
+* 0.1.2
+ - Fix documentation warnings.
+ - Update dependencies.
+* 0.1.1
+ - Documentation fixes.
+* 0.1.0
+ - Initial release.
+
+License
+-------
+
+btoi is dual licensed under the [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0)
+and [MIT](http://opensource.org/licenses/MIT) license, at your option.
diff --git a/vendor/btoi/benches/benches.rs b/vendor/btoi/benches/benches.rs
new file mode 100644
index 000000000..51e0921bc
--- /dev/null
+++ b/vendor/btoi/benches/benches.rs
@@ -0,0 +1,85 @@
+#[macro_use]
+extern crate bencher;
+extern crate btoi;
+
+use bencher::{black_box, Bencher};
+
+fn bench_btou(b: &mut Bencher) {
+ b.iter(|| assert_eq!(Ok(123_456_789u32), btoi::btou(black_box(b"123456789"))));
+}
+
+fn bench_btou_saturating(b: &mut Bencher) {
+ b.iter(|| {
+ assert_eq!(
+ Ok(123_456_789u32),
+ btoi::btou_saturating(black_box(b"123456789"))
+ )
+ });
+}
+
+fn bench_small_btou(b: &mut Bencher) {
+ b.iter(|| assert_eq!(Ok(42u8), btoi::btou(black_box(b"42"))));
+}
+
+fn bench_small_btou_saturating(b: &mut Bencher) {
+ b.iter(|| assert_eq!(Ok(255u8), btoi::btou_saturating(black_box(b"256"))));
+}
+
+fn bench_btoi(b: &mut Bencher) {
+ b.iter(|| assert_eq!(Ok(-123_456_789i32), btoi::btoi(black_box(b"-123456789"))));
+}
+
+fn bench_from_str(b: &mut Bencher) {
+ fn btou_from_str(s: &[u8]) -> Option<u32> {
+ ::std::str::from_utf8(s).ok().and_then(|s| s.parse().ok())
+ }
+
+ b.iter(|| assert_eq!(Some(123_456_789), btou_from_str(black_box(b"123456789"))));
+}
+
+fn bench_from_str_unchecked(b: &mut Bencher) {
+ unsafe fn btou_from_str_unchecked(s: &[u8]) -> Option<u32> {
+ ::std::str::from_utf8_unchecked(s).parse().ok()
+ }
+
+ b.iter(|| {
+ assert_eq!(Some(123_456_789), unsafe {
+ btou_from_str_unchecked(black_box(b"123456789"))
+ })
+ });
+}
+
+fn bench_small_from_str(b: &mut Bencher) {
+ fn btou_from_str(s: &[u8]) -> Option<u8> {
+ ::std::str::from_utf8(s).ok().and_then(|s| s.parse().ok())
+ }
+
+ b.iter(|| assert_eq!(Some(42u8), btou_from_str(black_box(b"42"))));
+}
+
+fn bench_small_from_str_unchecked(b: &mut Bencher) {
+ unsafe fn btou_from_str_unchecked(s: &[u8]) -> Option<u8> {
+ ::std::str::from_utf8_unchecked(s).parse().ok()
+ }
+
+ b.iter(|| {
+ assert_eq!(Some(42u8), unsafe {
+ btou_from_str_unchecked(black_box(b"42"))
+ })
+ });
+}
+
+benchmark_group!(
+ benches,
+ bench_btou,
+ bench_btou_saturating,
+ bench_btoi,
+ bench_from_str,
+ bench_from_str_unchecked,
+ bench_small_btou,
+ bench_small_btou_saturating,
+ bench_small_from_str,
+ bench_small_from_str_unchecked
+);
+
+benchmark_main!(benches);
diff --git a/vendor/btoi/rustfmt.toml b/vendor/btoi/rustfmt.toml
new file mode 100644
index 000000000..455c8209c
--- /dev/null
+++ b/vendor/btoi/rustfmt.toml
@@ -0,0 +1,2 @@
+imports_granularity = "Crate"
+group_imports = "StdExternalCrate"
diff --git a/vendor/btoi/src/lib.rs b/vendor/btoi/src/lib.rs
new file mode 100644
index 000000000..8271d1d75
--- /dev/null
+++ b/vendor/btoi/src/lib.rs
@@ -0,0 +1,659 @@
+// Copyright 2017-2023 Niklas Fiekas <niklas.fiekas@backscattering.de>
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Parse integers from ASCII byte slices.
+//!
+//! Provides functions similar to [`from_str_radix`], but is faster when
+//! parsing directly from byte slices instead of strings.
+//!
+//! Supports `#![no_std]`.
+//!
+//! # Examples
+//!
+//! ```
+//! use btoi::btoi;
+//!
+//! assert_eq!(Ok(42), btoi(b"42"));
+//! assert_eq!(Ok(-1000), btoi(b"-1000"));
+//! ```
+//!
+//! All functions are [generic](https://docs.rs/num-traits/) over integer
+//! types. Use the turbofish syntax if a type cannot be inferred from the
+//! context.
+//!
+//! ```
+//! # use btoi::btoi;
+//! // overflows the selected target type
+//! assert!(btoi::<u32>(b"9876543210").is_err());
+//!
+//! // underflows the selected target type (an unsigned integer)
+//! assert!(btoi::<u32>(b"-1").is_err());
+//! ```
+//!
+//! It is possible to use saturating arithmetic for overflow handling.
+//!
+//! ```
+//! use btoi::btoi_saturating;
+//!
+//! assert_eq!(Ok(0xffff_ffff), btoi_saturating::<u32>(b"9876543210"));
+//! assert_eq!(Ok(0), btoi_saturating::<u32>(b"-1"));
+//! ```
+//!
+//! # Errors
+//!
+//! All functions return [`ParseIntegerError`] for these error conditions:
+//!
+//! * The byte slice does not contain any digits.
+//! * Not all characters are `0-9`, `a-z`, `A-Z`. Leading or trailing
+//! whitespace is not allowed. The `btoi*` functions accept an optional
+//! leading `+` or `-` sign. The `btou*` functions respectively do not
+//! allow signs.
+//! * Not all digits are valid in the given radix.
+//! * The number overflows or underflows the target type, but saturating
+//! arithmetic is not used.
+//!
+//! # Panics
+//!
+//! Just like `from_str_radix` functions will panic if the given radix is
+//! not in the range `2..=36` (or in the pathological case that there is
+//! no representation of the radix in the target integer type).
+//!
+//! [`ParseIntegerError`]: struct.ParseIntegerError.html
+//! [`from_str_radix`]: https://doc.rust-lang.org/std/primitive.u32.html#method.from_str_radix
+
+#![doc(html_root_url = "https://docs.rs/btoi/0.4.3")]
+#![forbid(unsafe_code)]
+#![deny(missing_docs)]
+#![deny(missing_debug_implementations)]
+#![cfg_attr(not(feature = "std"), no_std)]
+
+extern crate num_traits;
+
+#[cfg(test)]
+#[macro_use]
+extern crate quickcheck;
+#[cfg(feature = "std")]
+extern crate std as core;
+
+use core::fmt;
+#[cfg(feature = "std")]
+use std::error::Error;
+
+use num_traits::{Bounded, CheckedAdd, CheckedMul, CheckedSub, FromPrimitive, Saturating, Zero};
+
+/// An error that can occur when parsing an integer.
+///
+/// * No digits
+/// * Invalid digit
+/// * Overflow
+/// * Underflow
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ParseIntegerError {
+ kind: ErrorKind,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ErrorKind {
+ Empty,
+ InvalidDigit,
+ Overflow,
+ Underflow,
+}
+
+impl ParseIntegerError {
+ fn desc(&self) -> &str {
+ match self.kind {
+ ErrorKind::Empty => "cannot parse integer without digits",
+ ErrorKind::InvalidDigit => "invalid digit found in slice",
+ ErrorKind::Overflow => "number too large to fit in target type",
+ ErrorKind::Underflow => "number too small to fit in target type",
+ }
+ }
+}
+
+impl fmt::Display for ParseIntegerError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.desc().fmt(f)
+ }
+}
+
+#[cfg(feature = "std")]
+impl Error for ParseIntegerError {
+ fn description(&self) -> &str {
+ self.desc()
+ }
+}
+
+/// Converts a byte slice in a given base to an integer. Signs are not allowed.
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` is empty
+/// * not all characters of `bytes` are `0-9`, `a-z` or `A-Z`
+/// * not all characters refer to digits in the given `radix`
+/// * the number overflows `I`
+///
+/// # Panics
+///
+/// Panics if `radix` is not in the range `2..=36` (or in the pathological
+/// case that there is no representation of `radix` in `I`).
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btou_radix;
+/// assert_eq!(Ok(255), btou_radix(b"ff", 16));
+/// assert_eq!(Ok(42), btou_radix(b"101010", 2));
+/// ```
+///
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btou_radix<I>(bytes: &[u8], radix: u32) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedAdd + CheckedMul,
+{
+ assert!(
+ (2..=36).contains(&radix),
+ "radix must lie in the range 2..=36, found {}",
+ radix
+ );
+
+ let base = I::from_u32(radix).expect("radix can be represented as integer");
+
+ if bytes.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let mut result = I::zero();
+
+ for &digit in bytes {
+ let x = match char::from(digit).to_digit(radix).and_then(I::from_u32) {
+ Some(x) => x,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::InvalidDigit,
+ })
+ }
+ };
+ result = match result.checked_mul(&base) {
+ Some(result) => result,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Overflow,
+ })
+ }
+ };
+ result = match result.checked_add(&x) {
+ Some(result) => result,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Overflow,
+ })
+ }
+ };
+ }
+
+ Ok(result)
+}
+
+/// Converts a byte slice to an integer. Signs are not allowed.
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` is empty
+/// * not all characters of `bytes` are `0-9`
+/// * the number overflows `I`
+///
+/// # Panics
+///
+/// Panics in the pathological case that there is no representation of `10`
+/// in `I`.
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btou;
+/// assert_eq!(Ok(12345), btou(b"12345"));
+/// assert!(btou::<u8>(b"+1").is_err()); // only btoi allows signs
+/// assert!(btou::<u8>(b"256").is_err()); // overflow
+/// ```
+///
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btou<I>(bytes: &[u8]) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedAdd + CheckedMul,
+{
+ btou_radix(bytes, 10)
+}
+
+/// Converts a byte slice in a given base to an integer.
+///
+/// Like [`btou_radix`], but numbers may optionally start with a sign
+/// (`-` or `+`).
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` has no digits
+/// * not all characters of `bytes` are `0-9`, `a-z`, `A-Z`, exluding an
+/// optional leading sign
+/// * not all characters refer to digits in the given `radix`, exluding an
+/// optional leading sign
+/// * the number overflows or underflows `I`
+///
+/// # Panics
+///
+/// Panics if `radix` is not in the range `2..=36` (or in the pathological
+/// case that there is no representation of `radix` in `I`).
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btoi_radix;
+/// assert_eq!(Ok(10), btoi_radix(b"a", 16));
+/// assert_eq!(Ok(10), btoi_radix(b"+a", 16));
+/// assert_eq!(Ok(-42), btoi_radix(b"-101010", 2));
+/// ```
+///
+/// [`btou_radix`]: fn.btou_radix.html
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btoi_radix<I>(bytes: &[u8], radix: u32) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedAdd + CheckedSub + CheckedMul,
+{
+ assert!(
+ (2..=36).contains(&radix),
+ "radix must lie in the range 2..=36, found {}",
+ radix
+ );
+
+ let base = I::from_u32(radix).expect("radix can be represented as integer");
+
+ if bytes.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let digits = match bytes[0] {
+ b'+' => return btou_radix(&bytes[1..], radix),
+ b'-' => &bytes[1..],
+ _ => return btou_radix(bytes, radix),
+ };
+
+ if digits.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let mut result = I::zero();
+
+ for &digit in digits {
+ let x = match char::from(digit).to_digit(radix).and_then(I::from_u32) {
+ Some(x) => x,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::InvalidDigit,
+ })
+ }
+ };
+ result = match result.checked_mul(&base) {
+ Some(result) => result,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Underflow,
+ })
+ }
+ };
+ result = match result.checked_sub(&x) {
+ Some(result) => result,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Underflow,
+ })
+ }
+ };
+ }
+
+ Ok(result)
+}
+
+/// Converts a byte slice to an integer.
+///
+/// Like [`btou`], but numbers may optionally start with a sign (`-` or `+`).
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` has no digits
+/// * not all characters of `bytes` are `0-9`, excluding an optional leading
+/// sign
+/// * the number overflows or underflows `I`
+///
+/// # Panics
+///
+/// Panics in the pathological case that there is no representation of `10`
+/// in `I`.
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btoi;
+/// assert_eq!(Ok(123), btoi(b"123"));
+/// assert_eq!(Ok(123), btoi(b"+123"));
+/// assert_eq!(Ok(-123), btoi(b"-123"));
+///
+/// assert!(btoi::<i16>(b"123456789").is_err()); // overflow
+/// assert!(btoi::<u32>(b"-1").is_err()); // underflow
+///
+/// assert!(btoi::<i32>(b" 42").is_err()); // leading space
+/// ```
+///
+/// [`btou`]: fn.btou.html
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btoi<I>(bytes: &[u8]) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedAdd + CheckedSub + CheckedMul,
+{
+ btoi_radix(bytes, 10)
+}
+
+/// Converts a byte slice in a given base to the closest possible integer.
+/// Signs are not allowed.
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` is empty
+/// * not all characters of `bytes` are `0-9`, `a-z`, `A-Z`
+/// * not all characters refer to digits in the given `radix`
+///
+/// # Panics
+///
+/// Panics if `radix` is not in the range `2..=36` (or in the pathological
+/// case that there is no representation of `radix` in `I`).
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btou_saturating_radix;
+/// assert_eq!(Ok(255), btou_saturating_radix::<u8>(b"00ff", 16));
+/// assert_eq!(Ok(255), btou_saturating_radix::<u8>(b"0100", 16)); // u8 saturated
+/// assert_eq!(Ok(255), btou_saturating_radix::<u8>(b"0101", 16)); // u8 saturated
+/// ```
+///
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btou_saturating_radix<I>(bytes: &[u8], radix: u32) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedMul + Saturating + Bounded,
+{
+ assert!(
+ (2..=36).contains(&radix),
+ "radix must lie in the range 2..=36, found {}",
+ radix
+ );
+
+ let base = I::from_u32(radix).expect("radix can be represented as integer");
+
+ if bytes.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let mut result = I::zero();
+
+ for &digit in bytes {
+ let x = match char::from(digit).to_digit(radix).and_then(I::from_u32) {
+ Some(x) => x,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::InvalidDigit,
+ })
+ }
+ };
+ result = match result.checked_mul(&base) {
+ Some(result) => result,
+ None => return Ok(I::max_value()),
+ };
+ result = result.saturating_add(x);
+ }
+
+ Ok(result)
+}
+
+/// Converts a byte slice to the closest possible integer.
+/// Signs are not allowed.
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` is empty
+/// * not all characters of `bytes` are `0-9`
+///
+/// # Panics
+///
+/// Panics in the pathological case that there is no representation of `10`
+/// in `I`.
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btou_saturating;
+/// assert_eq!(Ok(65535), btou_saturating::<u16>(b"65535"));
+/// assert_eq!(Ok(65535), btou_saturating::<u16>(b"65536")); // u16 saturated
+/// assert_eq!(Ok(65535), btou_saturating::<u16>(b"65537")); // u16 saturated
+/// ```
+///
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btou_saturating<I>(bytes: &[u8]) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedMul + Saturating + Bounded,
+{
+ btou_saturating_radix(bytes, 10)
+}
+
+/// Converts a byte slice in a given base to the closest possible integer.
+///
+/// Like [`btou_saturating_radix`], but numbers may optionally start with a
+/// sign (`-` or `+`).
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` has no digits
+/// * not all characters of `bytes` are `0-9`, `a-z`, `A-Z`, excluding an
+/// optional leading sign
+/// * not all characters refer to digits in the given `radix`, excluding an
+/// optional leading sign
+///
+/// # Panics
+///
+/// Panics if `radix` is not in the range `2..=36` (or in the pathological
+/// case that there is no representation of `radix` in `I`).
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btoi_saturating_radix;
+/// assert_eq!(Ok(127), btoi_saturating_radix::<i8>(b"7f", 16));
+/// assert_eq!(Ok(127), btoi_saturating_radix::<i8>(b"ff", 16)); // no overflow
+/// assert_eq!(Ok(-128), btoi_saturating_radix::<i8>(b"-ff", 16)); // no underflow
+/// ```
+///
+/// [`btou_saturating_radix`]: fn.btou_saturating_radix.html
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btoi_saturating_radix<I>(bytes: &[u8], radix: u32) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedMul + Saturating + Bounded,
+{
+ assert!(
+ (2..=36).contains(&radix),
+ "radix must lie in the range 2..=36, found {}",
+ radix
+ );
+
+ let base = I::from_u32(radix).expect("radix can be represented as integer");
+
+ if bytes.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let digits = match bytes[0] {
+ b'+' => return btou_saturating_radix(&bytes[1..], radix),
+ b'-' => &bytes[1..],
+ _ => return btou_saturating_radix(bytes, radix),
+ };
+
+ if digits.is_empty() {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::Empty,
+ });
+ }
+
+ let mut result = I::zero();
+
+ for &digit in digits {
+ let x = match char::from(digit).to_digit(radix).and_then(I::from_u32) {
+ Some(x) => x,
+ None => {
+ return Err(ParseIntegerError {
+ kind: ErrorKind::InvalidDigit,
+ })
+ }
+ };
+ result = match result.checked_mul(&base) {
+ Some(result) => result,
+ None => return Ok(I::min_value()),
+ };
+ result = result.saturating_sub(x);
+ }
+
+ Ok(result)
+}
+
+/// Converts a byte slice to the closest possible integer.
+///
+/// Like [`btou_saturating`], but numbers may optionally start with a sign
+/// (`-` or `+`).
+///
+/// # Errors
+///
+/// Returns [`ParseIntegerError`] for any of the following conditions:
+///
+/// * `bytes` has no digits
+/// * not all characters of `bytes` are `0-9`, excluding an optional leading
+/// sign
+///
+/// # Panics
+///
+/// Panics in the pathological case that there is no representation of `10`
+/// in `I`.
+///
+/// # Examples
+///
+/// ```
+/// # use btoi::btoi_saturating;
+/// assert_eq!(Ok(127), btoi_saturating::<i8>(b"127"));
+/// assert_eq!(Ok(127), btoi_saturating::<i8>(b"128")); // i8 saturated
+/// assert_eq!(Ok(127), btoi_saturating::<i8>(b"+1024")); // i8 saturated
+/// assert_eq!(Ok(-128), btoi_saturating::<i8>(b"-128"));
+/// assert_eq!(Ok(-128), btoi_saturating::<i8>(b"-129")); // i8 saturated
+///
+/// assert_eq!(Ok(0), btoi_saturating::<u32>(b"-123")); // unsigned integer saturated
+/// ```
+///
+/// [`btou_saturating`]: fn.btou_saturating.html
+/// [`ParseIntegerError`]: struct.ParseIntegerError.html
+#[track_caller]
+pub fn btoi_saturating<I>(bytes: &[u8]) -> Result<I, ParseIntegerError>
+where
+ I: FromPrimitive + Zero + CheckedMul + Saturating + Bounded,
+{
+ btoi_saturating_radix(bytes, 10)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::str;
+
+ use super::*;
+
+ quickcheck! {
+ fn btou_identity(n: u32) -> bool {
+ Ok(n) == btou(n.to_string().as_bytes())
+ }
+
+ fn btou_binary_identity(n: u64) -> bool {
+ Ok(n) == btou_radix(format!("{:b}", n).as_bytes(), 2)
+ }
+
+ fn btou_octal_identity(n: u64) -> bool {
+ Ok(n) == btou_radix(format!("{:o}", n).as_bytes(), 8)
+ }
+
+ fn btou_lower_hex_identity(n: u64) -> bool {
+ Ok(n) == btou_radix(format!("{:x}", n).as_bytes(), 16)
+ }
+
+ fn btou_upper_hex_identity(n: u64) -> bool {
+ Ok(n) == btou_radix(format!("{:X}", n).as_bytes(), 16)
+ }
+
+ fn btoi_identity(n: i32) -> bool {
+ Ok(n) == btoi(n.to_string().as_bytes())
+ }
+
+ fn btou_saturating_identity(n: u32) -> bool {
+ Ok(n) == btou_saturating(n.to_string().as_bytes())
+ }
+
+ fn btoi_saturating_identity(n: i32) -> bool {
+ Ok(n) == btoi_saturating(n.to_string().as_bytes())
+ }
+
+ fn btoi_radix_std(bytes: Vec<u8>, radix: u32) -> bool {
+ let radix = radix % 35 + 2; // panic unless 2 <= radix <= 36
+ str::from_utf8(&bytes).ok().and_then(|src| i32::from_str_radix(src, radix).ok()) ==
+ btoi_radix(&bytes, radix).ok()
+ }
+ }
+
+ #[test]
+ fn test_lone_minus() {
+ assert!(btoi::<isize>(b"-").is_err());
+ assert!(btoi_radix::<isize>(b"-", 16).is_err());
+ assert!(btoi_saturating::<isize>(b"-").is_err());
+ assert!(btoi_saturating_radix::<isize>(b"-", 8).is_err());
+
+ assert!(btou::<isize>(b"-").is_err());
+ assert!(btou_radix::<isize>(b"-", 16).is_err());
+ assert!(btou_saturating::<isize>(b"-").is_err());
+ assert!(btou_saturating_radix::<isize>(b"-", 8).is_err());
+ }
+}