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
#[cfg(feature = "bigint")]
use num_bigint::BigUint;
#[cfg(feature = "bigint")]
type Counter = BigUint;
#[cfg(not(feature = "bigint"))]
type Counter = u128;
use num_traits::cast::ToPrimitive;
use num_traits::{One, Zero};
pub const DEFAULT_RANGE: [char; 52] = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
#[derive(Clone)]
pub struct CharCombinator<'a> {
current: Counter,
range: &'a [char],
}
impl<'a> CharCombinator<'a> {
pub fn new(range: &'a [char]) -> CharCombinator<'a> {
CharCombinator {
current: Zero::zero(),
range,
}
}
pub fn new_from(start: Counter, range: &'a [char]) -> CharCombinator<'a> {
CharCombinator {
current: start,
range,
}
}
pub fn current(&self) -> &Counter {
&self.current
}
}
impl Default for CharCombinator<'static> {
fn default() -> Self {
CharCombinator::new(&DEFAULT_RANGE)
}
}
#[inline(always)]
fn to_letters(range: &[char], u: &Counter) -> String {
let mut result = String::new();
let mut quotient = u.clone();
let range_len: Counter = (range.len() as u64).into();
while quotient != Zero::zero() {
let decremented = quotient - Counter::from(1u64);
quotient = &decremented / &range_len;
let remainder = &decremented % &range_len;
if cfg!(target_pointer_width = "64") {
result = range[remainder.to_u64().unwrap() as usize].to_string() + &result;
} else {
result = range[remainder.to_u32().unwrap() as usize].to_string() + &result;
}
}
return result;
}
impl<'a> Iterator for CharCombinator<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
let one: Counter = One::one();
self.current += one;
Some(to_letters(&self.range, &self.current))
}
}
#[cfg(test)]
mod tests {
use crate::CharCombinator;
#[test]
fn default() {
assert_eq!(CharCombinator::default().skip(1024).nth(0).unwrap(), "sK");
}
#[test]
fn with_range() {
assert_eq!(
CharCombinator::new(&vec!['a', 'b', 'c'])
.skip(1024)
.nth(0)
.unwrap(),
"ccabbb"
);
}
#[test]
fn start_at() {
assert_eq!(
CharCombinator::new_from(1024u64.into(), &vec!['a', 'b', 'c'])
.nth(0)
.unwrap(),
"ccabbb"
);
}
}