1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
pub const ASCII_TO_INT_FACTOR: u8 = 48;

const POW10_U8_LEN: usize = 3;
const POW10_U16_LEN: usize = 5;
pub const POW10_U32_LEN: usize = 10;
pub const POW10_U64_LEN: usize = 20;

//all powers of 10 that fit in a u8
const POW10_U8: [u8; 3] = [100, 10, 1];

const POW10_U16: [u16; 5] = [10_000, 1_000, 100, 10, 1];

pub const POW10_U32: [u32; 10] = [
    1_000_000_000,
    100_000_000,
    10_000_000,
    1_000_000,
    100_000,
    10_000,
    1_000,
    100,
    10,
    1,
];

pub const POW10_U64: [u64; 20] = [
    10_000_000_000_000_000_000,
    1_000_000_000_000_000_000,
    100_000_000_000_000_000,
    10_000_000_000_000_000,
    1_000_000_000_000_000,
    100_000_000_000_000,
    10_000_000_000_000,
    1_000_000_000_000,
    100_000_000_000,
    10_000_000_000,
    1_000_000_000,
    100_000_000,
    10_000_000,
    1_000_000,
    100_000,
    10_000,
    1_000,
    100,
    10,
    1,
];

/// This trait allows convertion from bytes to integers.
pub trait FromAscii: Sized {
    /// The function performing the conversion. It takes anything that can be transformed into a byte-slice.
    /// # Examples
    /// ```
    /// extern crate byte_num;
    /// use byte_num::convert::FromAscii;
    ///
    /// fn main() {
    ///     assert_eq!(u32::atoi("1928"), Ok(1928));
    ///     assert_eq!(u32::atoi("12e3"), Err(()));
    /// }
    /// ```
    /// # Safety
    /// It should be noted that trying to convert a string that does not fit in the chosen integer type,
    /// wraps around.
    /// For example:
    /// ```
    /// extern crate byte_num;
    /// use byte_num::convert::FromAscii;
    ///
    /// fn main () {
    ///     let n = u8::atoi("257");
    ///     assert_eq!(n, Ok(1));
    /// }
    ///```
    #[inline]
    fn atoi<S: AsRef<[u8]>>(s: S) -> Result<Self, ()> {
        Self::bytes_to_int(s.as_ref())
    }

    /// Performs the actual conversion from a byteslice to an unsigned integer.
    fn bytes_to_int(s: &[u8]) -> Result<Self, ()>;
}

/// This trait converts integers to bytes.
pub trait IntoAscii {
    /// The function performing the convertion.
    /// # Examples
    /// ```
    /// extern crate byte_num;
    /// use byte_num::convert::IntoAscii;
    ///
    /// fn main() {
    ///     assert_eq!(12345u32.itoa(), [b'1', b'2', b'3', b'4', b'5']);
    /// }
    /// ```
    #[inline]
    fn itoa(&self) -> Vec<u8>
    where
        Self: Copy,
    {
        let size = Self::digits10(*self);
        let mut buff = vec![0; size];

        self.int_to_bytes(&mut buff);
        buff
    }

    /// Returns the size of an integer. This is how many digits the integer has.
    fn digits10(self) -> usize;

    /// Performs the actual convertion. It fills the given buff with bytes.
    /// Due to how the algorithm works, the last elements of the buffer get written to first.
    /// The buffer should have a size such that it can hold all the bytes.
    /// To get the size of an integer would take, use [`digits10()`](trait.IntoAscii.html#tymethod.digits10).
    /// # Examples
    /// ```
    /// extern crate byte_num;
    /// use byte_num::convert::IntoAscii;
    ///
    /// fn main() {
    ///     let mut v = vec![0, 0, 0, 0, 0];
    ///
    ///     12345u32.int_to_bytes(&mut v);
    ///     assert_eq!(v, [b'1', b'2', b'3', b'4', b'5']);
    ///
    ///     54321u64.int_to_bytes(&mut v);
    ///     assert_eq!(v, [b'5', b'4', b'3', b'2', b'1']);
    ///
    ///     // if the buffer is larger than the number of digits, it fills with 0.
    ///     123u8.int_to_bytes(&mut v);
    ///     assert_eq!(v, [b'5', b'4', b'1', b'2', b'3']);
    ///
    ///     // use slicing to collect 2 numbers into the buffer:
    ///
    ///     12u8.int_to_bytes(&mut v[..2]);
    ///     648u32.int_to_bytes(&mut v[2..]);
    ///     assert_eq!(v, [b'1', b'2', b'6', b'4', b'8']);
    ///
    /// }
    fn int_to_bytes(self, buff: &mut [u8]);
}

macro_rules! atoi_unroll {
    ($d:ident, $r:ident, $bytes:expr, $idx:expr, $offset:expr, $const_table:ident) => {
        let $d = Self::from(
            $bytes
                .get_unchecked($offset)
                .wrapping_sub(ASCII_TO_INT_FACTOR),
        );

        //if the digit is greater than 9, something went terribly horribly wrong.
        //return an Err(())
        if $d > 9 {
            return Err(());
        }
        let $r = $d * $const_table.get_unchecked($idx + $offset);
    };
}

macro_rules! impl_unsigned_conversions {
    ($int:ty, $const_table:ident, $const_table_len:ident) => {
        impl FromAscii for $int {
            #[inline]
            fn bytes_to_int(mut bytes: &[u8]) -> Result<Self, ()> {
                let mut result: Self = 0;
                let mut len: usize = bytes.len();
                let mut idx: usize = $const_table_len - len;

                unsafe {
                    while len >= 4 {
                        atoi_unroll!(d1, r1, bytes, idx, 0, $const_table);
                        atoi_unroll!(d2, r2, bytes, idx, 1, $const_table);
                        atoi_unroll!(d3, r3, bytes, idx, 2, $const_table);
                        atoi_unroll!(d4, r4, bytes, idx, 3, $const_table);

                        /*
                            @NOTE: changed `result += r1 + r2 + r3 + r4;` to the wrapping add version on 1 august 2018,
                            to prevent debug builds from panicing due to overflow.
                        */
                        result = result.wrapping_add(r1 + r2 + r3 + r4);

                        len -= 4;
                        idx += 4;
                        bytes = bytes.get_unchecked(4..);
                    }

                    for offset in 0..len {
                        atoi_unroll!(d, r, bytes, idx, offset, $const_table);
                        result += r;
                    }
                    return Ok(result);
                }
            }
        }

        impl IntoAscii for $int {
            #[inline]
            fn digits10(mut self) -> usize {
                let mut result = 1;

                loop {
                    if self < 10 { return result }
                    if self < 100 { return result + 1 }
                    if self < 1000 { return result + 2 }
                    if self < 10000 { return result + 3 }

                    self /= 10_000;
                    result += 4;
                }
            }

            #[inline]
            fn int_to_bytes(mut self, buff: &mut [u8]) {
                let mut len = buff.len();

                while self >= 10_000 {
                    let q = self / 10;
                    let q1 = self / 100;
                    let q2 = self / 1000;

                    let r = (self % 10) as u8 + ASCII_TO_INT_FACTOR;
                    let r1 = (q % 10) as u8 + ASCII_TO_INT_FACTOR;
                    let r2 = (q1 % 10) as u8 + ASCII_TO_INT_FACTOR;
                    let r3 = (q2 % 10) as u8 + ASCII_TO_INT_FACTOR;

                    // update the last 4 indecies
                    unsafe {
                        *buff.get_unchecked_mut(len - 1) = r;
                        *buff.get_unchecked_mut(len - 2) = r1;
                        *buff.get_unchecked_mut(len - 3) = r2;
                        *buff.get_unchecked_mut(len - 4) = r3;
                    }

                    len -= 4;
                    self /= 10_000;
                }

                //fixup loop. This might not be run if self was a multiple of 10_000
                for byte in unsafe { buff.get_unchecked_mut(..len) }.iter_mut().rev() {
                    let q = self / 10;
                    let r = (self % 10) as u8 + ASCII_TO_INT_FACTOR;
                    *byte = r;

                    //there's nothing more to do.
                    if q == 0 {
                        return;
                    }

                    self = q;
                }
            }
        }
    };
}

//this implementation is different than for all other unsigned integers. max u8 is 255, which only has a length of 3.
impl FromAscii for u8 {
    #[inline]
    fn bytes_to_int(bytes: &[u8]) -> Result<Self, ()> {
        let mut result: Self = 0;
        let len: usize = bytes.len();
        let idx = POW10_U8_LEN - len;
        unsafe {
            for offset in 0..len {
                atoi_unroll!(d, r, bytes, idx, offset, POW10_U8);

                // @NOTE: changed from `result += r` to this, due to overflow panics on debug builds.
                result = result.wrapping_add(r);
            }
            Ok(result)
        }
    }
}

impl IntoAscii for u8 {
    #[inline]
    fn digits10(self) -> usize {
        if self < 10 {
            1
        } else if self < 100 {
            2
        } else {
            3
        }
    }

    #[inline]
    fn int_to_bytes(mut self, buff: &mut [u8]) {
        let mut q;
        let mut r;

        for byte in buff.iter_mut().rev() {
            q = self / 10;
            r = (self % 10) as u8 + ASCII_TO_INT_FACTOR;
            *byte = r;
            self = q;

            if self == 0 {
                break;
            }
        }
    }
}

impl_unsigned_conversions!(u16, POW10_U16, POW10_U16_LEN);
impl_unsigned_conversions!(u32, POW10_U32, POW10_U32_LEN);
impl_unsigned_conversions!(u64, POW10_U64, POW10_U64_LEN);

#[cfg(target_pointer_width = "32")]
impl FromAscii for usize {
    #[inline]
    fn bytes_to_int(bytes: &[u8]) -> Result<Self, ()> {
        Ok(u32::bytes_to_int(bytes)? as Self)
    }
}

#[cfg(target_pointer_width = "64")]
impl FromAscii for usize {
    #[inline]
    fn bytes_to_int(bytes: &[u8]) -> Result<Self, ()> {
        Ok(u64::bytes_to_int(bytes)? as Self)
    }
}

macro_rules! impl_signed_conversions {
    ($int:ty, $unsigned_version:ty) => {
        impl FromAscii for $int {
            fn bytes_to_int(bytes: &[u8]) -> Result<Self, ()> {
                if bytes.starts_with(b"-") {
                    unsafe {
                        Ok(-(<$unsigned_version>::bytes_to_int(bytes.get_unchecked(1..))? as Self))
                    }
                } else {
                    Ok(<$unsigned_version>::bytes_to_int(bytes)? as Self)
                }
            }
        }

        impl IntoAscii for $int {
            fn itoa(&self) -> Vec<u8>
            where
                Self: Copy,
            {
                if self < &0 {
                    let n = self * -1;
                    let size = Self::digits10(n) + 1;

                    let mut buff = vec![0; size];
                    unsafe {
                        *buff.get_unchecked_mut(0) = b'-';
                    }
                    n.int_to_bytes(&mut buff);
                    buff
                } else {
                    let size = Self::digits10(*self);
                    let mut buff = vec![0; size];
                    self.int_to_bytes(&mut buff);
                    buff
                }
            }

            #[inline]
            fn digits10(self) -> usize {
                (self as $unsigned_version).digits10()
            }

            #[inline]
            fn int_to_bytes(self, buff: &mut [u8]) {
                (self as $unsigned_version).int_to_bytes(buff);
            }
        }
    };
}

#[cfg(target_pointer_width = "32")]
impl IntoAscii for usize {
    #[inline]
    fn digits10(self) -> Self {
        u32::digits10(self as u32)
    }

    #[inline]
    fn int_to_bytes(self, buff: &mut [u8]) {
        u32::int_to_bytes(self as u32, buff);
    }
}

#[cfg(target_pointer_width = "64")]
impl IntoAscii for usize {
    #[inline]
    fn digits10(self) -> Self {
        u64::digits10(self as u64)
    }

    #[inline]
    fn int_to_bytes(self, buff: &mut [u8]) {
        u64::int_to_bytes(self as u64, buff);
    }
}

impl_signed_conversions!(i8, u8);
impl_signed_conversions!(i16, u16);
impl_signed_conversions!(i32, u32);
impl_signed_conversions!(i64, u64);
impl_signed_conversions!(isize, usize);

#[cfg(test)]
mod test_parsing {
    use super::*;

    #[test]
    fn bytes_to_int() {
        assert_eq!(i32::atoi(b"-123"), Ok(-123));
        assert_eq!(i32::atoi(b"123"), Ok(123));

        assert_eq!(i32::atoi(b"123e"), Err(()));

        assert_eq!(isize::atoi(b"9223372036854775807"), Ok(isize::max_value()));
        assert_eq!(isize::atoi(b"9223372036854775808"), Ok(isize::min_value()));

        assert_eq!(usize::atoi(b"18446744073709551615"), Ok(usize::max_value()));
        assert_eq!(usize::atoi(b"18446744073709551616"), Ok(usize::min_value()));
    }
    #[test]
    fn test_itoa() {

        assert_eq!(9987u32.itoa(), [b'9', b'9', b'8', b'7']);

        assert_eq!(isize::max_value().itoa(), [b'9', b'2', b'2', b'3', b'3', b'7', b'2', b'0', b'3', b'6', b'8', b'5', b'4', b'7', b'7', b'5', b'8', b'0', b'7'])
    }
}