digits_iterator/
lib.rs

1//! This crate adds an extension method to the integers that permits
2//! to iterate over their digits.
3//!
4//! Note that the signed integers will be casted to the corresponding unsigned
5//! integers. Do not use this iterator with negative signed integers unless you
6//! *really* want to iterate over the digits of the complement.
7//!
8//! To use this extension, add the crate and import its content:
9//!
10//! ```
11//! extern crate digits_iterator;
12//! use digits_iterator::*;
13//! ```
14//!
15//! # Examples
16//!
17//! ```rust
18//! use digits_iterator::*;
19//!
20//! let digits: Vec<_> = 2018_u32.digits().collect();
21//! assert_eq!(digits[..], [2, 0, 1, 8]);
22//!
23//! let digits: Vec<_> = 0b101010.digits_with_base(2).collect();
24//! assert_eq!(digits[..], [1_u8, 0, 1, 0, 1, 0]);
25//! ```
26
27#![deny(missing_docs)]
28
29#[cfg(test)]
30mod tests;
31
32mod int;
33use int::Int;
34
35mod digits;
36use digits::Digits;
37
38/// Adds the extension methods to iterate over the digits of integers.
39pub trait DigitsExtension: Int {
40    /// Iterates over the digits of self in decimal base.
41    ///
42    /// # Example
43    ///
44    /// ```
45    /// use digits_iterator::*;
46    ///
47    /// let n = 2018_u32;
48    /// let digits: Vec<_> = n.digits().collect();
49    ///
50    /// assert_eq!(digits, [2, 0, 1, 8]);
51    /// ```
52    fn digits(self) -> Digits<Self> {
53        Digits::new(self)
54    }
55
56    /// Iterates over the digits of self in a base between 2 and 36.
57    ///
58    /// # Example
59    ///
60    /// ```
61    /// use digits_iterator::*;
62    ///
63    /// let n = 0b100101_u32;
64    /// let digits: Vec<_> = n.digits_with_base(2).collect();
65    ///
66    /// assert_eq!(digits, [1, 0, 0, 1, 0, 1]);
67    /// ```
68    fn digits_with_base(self, base: u32) -> Digits<Self> {
69        Digits::with_base(self, base)
70    }
71}
72
73impl<T> DigitsExtension for T
74where
75    T: Int,
76{
77}