Skip to content

Commit d784c63

Browse files
Jonathan SchleußerJonathan Schleußer
Jonathan Schleußer
authored and
Jonathan Schleußer
committed
Complete the impl macro cycle
1 parent ffb3dd9 commit d784c63

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

src/lib.rs

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,19 @@ macro_rules! impl_new {
6464
};
6565
}
6666

67+
macro_rules! impl_process_token {
68+
($elem_ty: ty, $inner_elem_ty: ty, $numbers_fun: expr, $letters_fun: expr) => {
69+
fn process_token(input: $elem_ty) -> ($inner_elem_ty, $elem_ty) {
70+
if let Some(pos_end) = (*NUMBERS).find(&input).map(|m| m.end()) {
71+
$numbers_fun(input, pos_end)
72+
} else {
73+
let pos_end = (*LETTERS).find(&input).unwrap().end();
74+
$letters_fun(input, pos_end)
75+
}
76+
}
77+
};
78+
}
79+
6780
macro_rules! impl_partial_ord {
6881
($elem_ident:ident, $struct:ident) => {
6982
#[inline]
@@ -114,18 +127,15 @@ pub struct HumanStr<'a> {
114127

115128
impl<'a> HumanStr<'a> {
116129
impl_new!(&'a str, HumanStr, HumanStr<'a>);
117-
118-
fn process_token(input: &'a str) -> (StrElem<'a>, &str) {
119-
if let Some(pos_end) = (*NUMBERS).find(input).map(|m| m.end()) {
120-
(
121-
StrElem::Number(BigInt::from_str(&input[..pos_end]).unwrap()),
122-
&input[pos_end..],
123-
)
124-
} else {
125-
let pos_end = (*LETTERS).find(input).unwrap().end();
126-
(StrElem::Letters(&input[..pos_end]), &input[pos_end..])
127-
}
128-
}
130+
impl_process_token!(
131+
&'a str,
132+
StrElem<'a>,
133+
|input: &'a str, pos_end| (
134+
StrElem::Number(BigInt::from_str(&input[..pos_end]).unwrap()),
135+
&input[pos_end..],
136+
),
137+
|input: &'a str, pos_end| (StrElem::Letters(&input[..pos_end]), &input[pos_end..])
138+
);
129139
}
130140

131141
/// A utility function for sorting a list of strings using human sorting.
@@ -167,23 +177,19 @@ pub struct HumanString {
167177

168178
impl HumanString {
169179
impl_new!(String, HumanString, HumanString);
170-
171-
fn process_token(mut input: String) -> (StringElem, String) {
172-
lazy_static! {
173-
static ref NUMBERS: Regex = Regex::new("^[0-9]+").unwrap();
174-
static ref LETTERS: Regex = Regex::new("^[^0-9]+").unwrap();
175-
}
176-
177-
if let Some(pos_end) = (*NUMBERS).find(&input).map(|m| m.end()) {
180+
impl_process_token!(
181+
String,
182+
StringElem,
183+
|mut input: String, pos_end| {
178184
let number = StringElem::Number(BigInt::from_str(&input[..pos_end]).unwrap());
179185
input.drain(..pos_end).count();
180186
(number, input)
181-
} else {
182-
let pos_end = (*LETTERS).find(&input).unwrap().end();
187+
},
188+
|mut input: String, pos_end| {
183189
let rest = input.split_off(pos_end - 1);
184190
(StringElem::Letters(input), rest)
185191
}
186-
}
192+
);
187193
}
188194

189195
impl PartialOrd for HumanString {

0 commit comments

Comments
 (0)