Skip to content

Commit cb028dc

Browse files
committed
librustdoc: create a helper for separating elements of an iterator instead of implementing it multiple times
1 parent c705b7d commit cb028dc

File tree

5 files changed

+202
-205
lines changed

5 files changed

+202
-205
lines changed

src/librustdoc/clean/cfg.rs

+40-19
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_span::Span;
1414
use rustc_span::symbol::{Symbol, sym};
1515

1616
use crate::html::escape::Escape;
17+
use crate::joined::Joined as _;
1718

1819
#[cfg(test)]
1920
mod tests;
@@ -396,6 +397,8 @@ impl Display<'_> {
396397
sub_cfgs: &[Cfg],
397398
separator: &str,
398399
) -> fmt::Result {
400+
use fmt::Display as _;
401+
399402
let short_longhand = self.1.is_long() && {
400403
let all_crate_features =
401404
sub_cfgs.iter().all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::feature, Some(_))));
@@ -414,20 +417,29 @@ impl Display<'_> {
414417
}
415418
};
416419

417-
for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
418-
if i != 0 {
419-
fmt.write_str(separator)?;
420-
}
421-
if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
422-
if self.1.is_html() {
423-
write!(fmt, "<code>{feat}</code>")?;
424-
} else {
425-
write!(fmt, "`{feat}`")?;
426-
}
427-
} else {
428-
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
429-
}
430-
}
420+
fmt::from_fn(|f| {
421+
sub_cfgs
422+
.iter()
423+
.map(|sub_cfg| {
424+
fmt::from_fn(move |fmt| {
425+
if let Cfg::Cfg(_, Some(feat)) = sub_cfg
426+
&& short_longhand
427+
{
428+
if self.1.is_html() {
429+
write!(fmt, "<code>{feat}</code>")?;
430+
} else {
431+
write!(fmt, "`{feat}`")?;
432+
}
433+
} else {
434+
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
435+
}
436+
Ok(())
437+
})
438+
})
439+
.joined(separator, f)
440+
})
441+
.fmt(fmt)?;
442+
431443
Ok(())
432444
}
433445
}
@@ -439,11 +451,20 @@ impl fmt::Display for Display<'_> {
439451
Cfg::Any(ref sub_cfgs) => {
440452
let separator =
441453
if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
442-
for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
443-
fmt.write_str(if i == 0 { "neither " } else { separator })?;
444-
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
445-
}
446-
Ok(())
454+
fmt.write_str("neither ")?;
455+
456+
sub_cfgs
457+
.iter()
458+
.map(|sub_cfg| {
459+
fmt::from_fn(|fmt| {
460+
write_with_opt_paren(
461+
fmt,
462+
!sub_cfg.is_all(),
463+
Display(sub_cfg, self.1),
464+
)
465+
})
466+
})
467+
.joined(separator, fmt)
447468
}
448469
ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Display(simple, self.1)),
449470
ref c => write!(fmt, "not ({})", Display(c, self.1)),

0 commit comments

Comments
 (0)