atoi-0.2.3/.gitignore000064400000000000000000000000561314544544700126420ustar0000000000000000target/ **/*.rs.bk Cargo.lock rls.toml .vscodeatoi-0.2.3/benches/lib.rs000064400000000000000000000010301312702737700133640ustar0000000000000000#![feature(test)] extern crate test; extern crate atoi; use atoi::FromRadix10; use std::str; #[bench] fn i32_four_digit_number(b: &mut test::Bencher) { b.iter(|| i32::from_radix_10(test::black_box(b"1996"))) } #[bench] fn u32_four_digit_number(b: &mut test::Bencher) { b.iter(|| u32::from_radix_10(test::black_box(b"1996"))) } #[bench] fn through_utf8(b: &mut test::Bencher) { b.iter(|| { let s = str::from_utf8(test::black_box(b"1996")).unwrap(); s.parse::().unwrap(); }) }atoi-0.2.3/Cargo.toml.orig000064400000000000000000000015731324734723100135410ustar0000000000000000[package] name = "atoi" version = "0.2.3" authors = ["Markus Klein "] license = "MIT" repository = "https://github.com/pacman82/atoi-rs" documentation = "https://docs.rs/atoi/" # A short blurb about the package. This is not rendered in any format when # uploaded to crates.io (aka this is not markdown). description = "Parse integers directly from `[u8]` slices in safe code" # This is a list of up to five keywords that describe this crate. Keywords # are searchable on crates.io, and you may choose any words that would # help someone find this crate. keywords = ["atoi", "conversion", "integer"] # This is a list of up to five categories where this crate would fit. # Categories are a fixed list available at crates.io/category_slugs, and # they must match exactly. categories = ["parsing"] [dependencies] num-traits="0.2.1" [dev-dependencies] checked = "0.5.0"atoi-0.2.3/Cargo.toml0000644000000016720000000000000100350ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "atoi" version = "0.2.3" authors = ["Markus Klein "] description = "Parse integers directly from `[u8]` slices in safe code" documentation = "https://docs.rs/atoi/" keywords = ["atoi", "conversion", "integer"] categories = ["parsing"] license = "MIT" repository = "https://github.com/pacman82/atoi-rs" [dependencies.num-traits] version = "0.2.1" [dev-dependencies.checked] version = "0.5.0" atoi-0.2.3/CONTRIBUTING.md000064400000000000000000000000701312702236200130620ustar0000000000000000Contributions are welcome! Just create a pull request. atoi-0.2.3/LICENSE000064400000000000000000000020661312504427100116460ustar0000000000000000MIT License Copyright (c) 2017 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. atoi-0.2.3/README.md000064400000000000000000000010421312702272100121070ustar0000000000000000# atoi-rs Parse integers directly from `[u8]` slices in safe code # Reasons to use this crate Starting from a binary or ascii format you can parse an integer around three times as fast as with the more idiomatic detour over utf8. The crate comes with benchmarks so you can see for yourself. # Example Parsing from a slice ```rust use atoi::atoi; assert_eq!(Some(42), atoi::(b"42")); ``` This [crate](https://www.crates.io/crates/atoi) as more to offer! Check out the full documentation at [docs.rs](https://docs.rs/atoi).atoi-0.2.3/src/lib.rs000064400000000000000000000130501324734703200125450ustar0000000000000000//! A crate for parsing integers directly form ASCII (`[u8]`) without encoding them into utf8 //! first. The name is inspired by the famous C function. //! //! Using `str::from_utf8` and `str::parse` //! is likely to be more idiomatic. Use this crate if you want to avoid decoding bytes into utf8 //! (e.g. for performance reasons). extern crate num_traits; use num_traits::{One, Signed, Zero}; use std::ops::{AddAssign, MulAssign}; /// Types implementing this trait can be parsed from a positional numeral system with radix 10 pub trait FromRadix10: Sized { /// Parses an integer from a slice. /// /// # Example /// /// ``` /// use atoi::FromRadix10; /// // Parsing to digits from a slice /// assert_eq!((42,2), u32::from_radix_10(b"42")); /// // Additional bytes after the number are ignored /// assert_eq!((42,2), u32::from_radix_10(b"42 is the answer to life, the universe and everything")); /// // (0,0) is returned if the slice does not start with a digit /// assert_eq!((0,0), u32::from_radix_10(b"Sadly we do not know the question")); /// // While signed integer types are supported... /// assert_eq!((42,2), i32::from_radix_10(b"42")); /// // Signs are not allowed (even for signed integer types) /// assert_eq!((0,0), i32::from_radix_10(b"-42")); /// // Leading zeros are allowed /// assert_eq!((42,4), u32::from_radix_10(b"0042")); /// ``` /// /// # Return /// Returns a tuple with two numbers. The first is the integer parsed or zero, the second is the /// index of the byte right after the parsed number. If the second element is zero the slice /// did not start with an ASCII digit. fn from_radix_10(&[u8]) -> (Self, usize); } /// Parses an integer from a slice. /// /// Contrary to its 'C' counterpart atoi is generic and will require a type argument if the type /// inference can not determine its result. /// /// # Example /// /// ``` /// use atoi::atoi; /// // Parsing to digits from a slice /// assert_eq!(Some(42), atoi::(b"42")); /// // Additional bytes after the number are ignored. If you want to know how many bytes were used /// // to parse the number use `FromRadix10::from_radix_10`. /// assert_eq!(Some(42), atoi::(b"42 is the answer to life, the universe and everything")); /// // `None` is returned if the slice does not start with a digit /// assert_eq!(None, atoi::(b"Sadly we do not know the question")); /// // While signed integer types are supported... /// assert_eq!(Some(42), atoi::(b"42")); /// // ... signs currently are not (subject to change in future versions) /// assert_eq!(None, atoi::(b"-42")); /// // Leading zeros are allowed /// assert_eq!(Some(42), atoi::(b"0042")); /// // By default this will panic in debug or overflow in release builds. /// // assert_eq!(Some(0), atoi::(b"256")). /// // use the e.g. the `checked` crate to handle overflows gracefully /// ``` /// /// # Return /// Returns a a number if the slice started with a number, otherwise `None` is returned. pub fn atoi(text: &[u8]) -> Option where I: FromRadix10, { match I::from_radix_10(text) { (_, 0) => None, (n, _) => Some(n), } } /// Converts an ascii character to digit /// /// # Example /// /// ``` /// use atoi::ascii_to_digit; /// assert_eq!(Some(5), ascii_to_digit(b'5')); /// assert_eq!(None, ascii_to_digit::(b'x')); /// ``` pub fn ascii_to_digit(character: u8) -> Option where I: Zero + One, { match character { b'0' => Some(nth(0)), b'1' => Some(nth(1)), b'2' => Some(nth(2)), b'3' => Some(nth(3)), b'4' => Some(nth(4)), b'5' => Some(nth(5)), b'6' => Some(nth(6)), b'7' => Some(nth(7)), b'8' => Some(nth(8)), b'9' => Some(nth(9)), _ => None, } } impl FromRadix10 for I where I: Zero + One + AddAssign + MulAssign, { fn from_radix_10(text: &[u8]) -> (Self, usize) { let mut index = 0; let mut number = I::zero(); while index != text.len() { if let Some(digit) = ascii_to_digit(text[index]) { number *= nth(10); number += digit; index += 1; } else { break; } } (number, index) } } /// Representation of a numerical sign #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Sign { Plus, Minus, } impl Sign { /// Trys to convert an ascii character into a `Sign` /// /// # Example /// /// ``` /// use atoi::Sign; /// assert_eq!(Some(Sign::Plus), Sign::try_from(b'+')); /// assert_eq!(Some(Sign::Minus), Sign::try_from(b'-')); /// assert_eq!(None, Sign::try_from(b'1')); /// ``` pub fn try_from(byte: u8) -> Option { match byte { b'+' => Some(Sign::Plus), b'-' => Some(Sign::Minus), _ => None, } } /// Returns either `+1` or `-1` pub fn signum(self) -> I where I: Signed, { match self { Sign::Plus => I::one(), Sign::Minus => -I::one(), } } } // At least for primitive types this function does not incur runtime costs, since it is only called // with constants fn nth(n: u8) -> I where I: Zero + One, { let mut i = I::zero(); for _ in 0..n { i = i + I::one(); } i } #[cfg(test)] mod test { extern crate checked; use self::checked::Checked; use super::*; #[test] fn overflow_detection() { assert_eq!(Some(Checked(None)), atoi::>(b"256")); } }