Make use of is_some_and where applicable (#3523)

This commit is contained in:
Laurenz 2024-02-28 15:24:50 +01:00 committed by GitHub
parent 9d8df00ffb
commit 8d63b0479c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 56 additions and 43 deletions

View File

@ -1178,7 +1178,7 @@ impl<'a> CompletionContext<'a> {
parens: bool, parens: bool,
docs: Option<&str>, docs: Option<&str>,
) { ) {
let at = label.as_deref().map_or(false, |field| !is_ident(field)); let at = label.as_deref().is_some_and(|field| !is_ident(field));
let label = label.unwrap_or_else(|| value.repr()); let label = label.unwrap_or_else(|| value.repr());
let detail = docs.map(Into::into).or_else(|| match value { let detail = docs.map(Into::into).or_else(|| match value {

View File

@ -55,7 +55,7 @@ pub(crate) fn write_outline(ctx: &mut PdfContext) -> Option<Ref> {
// exists), or at most as deep as its actual nesting level in Typst // exists), or at most as deep as its actual nesting level in Typst
// (not exceeding whichever is the most restrictive depth limit // (not exceeding whichever is the most restrictive depth limit
// of those two). // of those two).
while children.last().map_or(false, |last| { while children.last().is_some_and(|last| {
last_skipped_level.map_or(true, |l| last.level < l) last_skipped_level.map_or(true, |l| last.level < l)
&& last.level < leaf.level && last.level < leaf.level
}) { }) {

View File

@ -601,12 +601,12 @@ impl<'a> Raw<'a> {
let is_whitespace = |line: &&str| line.chars().all(char::is_whitespace); let is_whitespace = |line: &&str| line.chars().all(char::is_whitespace);
// Trims a sequence of whitespace followed by a newline at the start. // Trims a sequence of whitespace followed by a newline at the start.
if lines.first().map_or(false, is_whitespace) { if lines.first().is_some_and(is_whitespace) {
lines.remove(0); lines.remove(0);
} }
// Trims a newline followed by a sequence of whitespace at the end. // Trims a newline followed by a sequence of whitespace at the end.
if lines.last().map_or(false, is_whitespace) { if lines.last().is_some_and(is_whitespace) {
lines.pop(); lines.pop();
} }
} }

View File

@ -341,7 +341,7 @@ impl Lexer<'_> {
fn in_word(&self) -> bool { fn in_word(&self) -> bool {
let wordy = |c: Option<char>| { let wordy = |c: Option<char>| {
c.map_or(false, |c| { c.is_some_and(|c| {
c.is_alphanumeric() c.is_alphanumeric()
&& !matches!( && !matches!(
c.script(), c.script(),
@ -538,7 +538,7 @@ impl Lexer<'_> {
// Make sure not to confuse a range for the decimal separator. // Make sure not to confuse a range for the decimal separator.
if c != '.' if c != '.'
&& !self.s.at("..") && !self.s.at("..")
&& !self.s.scout(1).map_or(false, is_id_start) && !self.s.scout(1).is_some_and(is_id_start)
&& self.s.eat_if('.') && self.s.eat_if('.')
&& base == 10 && base == 10
{ {
@ -740,7 +740,7 @@ pub fn is_ident(string: &str) -> bool {
let mut chars = string.chars(); let mut chars = string.chars();
chars chars
.next() .next()
.map_or(false, |c| is_id_start(c) && chars.all(is_id_continue)) .is_some_and(|c| is_id_start(c) && chars.all(is_id_continue))
} }
/// Whether a character can start an identifier. /// Whether a character can start an identifier.

View File

@ -1709,7 +1709,7 @@ impl<'s> Parser<'s> {
fn unskip(&mut self) { fn unskip(&mut self) {
if self.lexer.mode() != LexMode::Markup && self.prev_end != self.current_start { if self.lexer.mode() != LexMode::Markup && self.prev_end != self.current_start {
while self.nodes.last().map_or(false, |last| last.kind().is_trivia()) { while self.nodes.last().is_some_and(|last| last.kind().is_trivia()) {
self.nodes.pop(); self.nodes.pop();
} }

View File

@ -139,7 +139,7 @@ impl<'a> Route<'a> {
impl<'a> Route<'a> { impl<'a> Route<'a> {
/// Whether the given id is part of the route. /// Whether the given id is part of the route.
pub fn contains(&self, id: FileId) -> bool { pub fn contains(&self, id: FileId) -> bool {
self.id == Some(id) || self.outer.map_or(false, |outer| outer.contains(id)) self.id == Some(id) || self.outer.is_some_and(|outer| outer.contains(id))
} }
/// Whether the route's depth is less than or equal to the given depth. /// Whether the route's depth is less than or equal to the given depth.

View File

@ -80,6 +80,17 @@ impl<T> Smart<T> {
matches!(self, Self::Custom(_)) matches!(self, Self::Custom(_))
} }
/// Whether this is a `Smart::Custom(x)` and `f(x)` is true.
pub fn is_custom_and<F>(self, f: F) -> bool
where
F: Fn(T) -> bool,
{
match self {
Self::Auto => false,
Self::Custom(x) => f(x),
}
}
/// Returns a `Smart<&T>` borrowing the inner `T`. /// Returns a `Smart<&T>` borrowing the inner `T`.
pub fn as_ref(&self) -> Smart<&T> { pub fn as_ref(&self) -> Smart<&T> {
match self { match self {
@ -88,9 +99,12 @@ impl<T> Smart<T> {
} }
} }
/// Returns a reference the contained custom value. /// Returns the contained custom value.
/// If the value is [`Smart::Auto`], `None` is returned. ///
pub fn as_custom(self) -> Option<T> { /// If the value is [`Smart::Auto`], returns `None`.
///
/// Equivalently, this just converts `Smart` to `Option`.
pub fn custom(self) -> Option<T> {
match self { match self {
Self::Auto => None, Self::Auto => None,
Self::Custom(x) => Some(x), Self::Custom(x) => Some(x),

View File

@ -306,7 +306,7 @@ impl Datetime {
) -> StrResult<Datetime> { ) -> StrResult<Datetime> {
Ok(engine Ok(engine
.world .world
.today(offset.as_custom()) .today(offset.custom())
.ok_or("unable to get the current date")?) .ok_or("unable to get the current date")?)
} }

View File

@ -140,7 +140,7 @@ impl Selector {
Self::Label(label) => target.label() == Some(*label), Self::Label(label) => target.label() == Some(*label),
Self::Regex(regex) => target Self::Regex(regex) => target
.to_packed::<TextElem>() .to_packed::<TextElem>()
.map_or(false, |elem| regex.is_match(elem.text())), .is_some_and(|elem| regex.is_match(elem.text())),
Self::Can(cap) => target.func().can_type_id(*cap), Self::Can(cap) => target.func().can_type_id(*cap),
Self::Or(selectors) => { Self::Or(selectors) => {
selectors.iter().any(move |sel| sel.matches(target, styles)) selectors.iter().any(move |sel| sel.matches(target, styles))

View File

@ -114,7 +114,7 @@ impl Str {
.and_then(|v| usize::try_from(v).ok()) .and_then(|v| usize::try_from(v).ok())
.filter(|&v| v <= self.0.len()); .filter(|&v| v <= self.0.len());
if resolved.map_or(false, |i| !self.0.is_char_boundary(i)) { if resolved.is_some_and(|i| !self.0.is_char_boundary(i)) {
return Err(not_a_char_boundary(index)); return Err(not_a_char_boundary(index));
} }
@ -308,7 +308,7 @@ impl Str {
) -> bool { ) -> bool {
match pattern { match pattern {
StrPattern::Str(pat) => self.0.starts_with(pat.as_str()), StrPattern::Str(pat) => self.0.starts_with(pat.as_str()),
StrPattern::Regex(re) => re.find(self).map_or(false, |m| m.start() == 0), StrPattern::Regex(re) => re.find(self).is_some_and(|m| m.start() == 0),
} }
} }

View File

@ -381,7 +381,7 @@ impl Recipe {
pub fn applicable(&self, target: &Content, styles: StyleChain) -> bool { pub fn applicable(&self, target: &Content, styles: StyleChain) -> bool {
self.selector self.selector
.as_ref() .as_ref()
.map_or(false, |selector| selector.matches(target, Some(styles))) .is_some_and(|selector| selector.matches(target, Some(styles)))
} }
/// Apply the recipe to the given content. /// Apply the recipe to the given content.

View File

@ -367,7 +367,7 @@ impl Counter {
styles: Option<StyleChain>, styles: Option<StyleChain>,
) -> SourceResult<Value> { ) -> SourceResult<Value> {
let numbering = numbering let numbering = numbering
.as_custom() .custom()
.or_else(|| { .or_else(|| {
let styles = styles?; let styles = styles?;
let CounterKey::Selector(Selector::Elem(func, _)) = self.0 else { let CounterKey::Selector(Selector::Elem(func, _)) = self.0 else {

View File

@ -493,7 +493,7 @@ impl<'a> FlowLayouter<'a> {
while self while self
.items .items
.last() .last()
.map_or(false, |item| matches!(item, FlowItem::Absolute(_, true))) .is_some_and(|item| matches!(item, FlowItem::Absolute(_, true)))
{ {
self.items.pop(); self.items.pop();
} }
@ -685,7 +685,7 @@ impl FlowLayouter<'_> {
// together). // together).
if !force if !force
&& (k == 0 || movable) && (k == 0 || movable)
&& frames.first().map_or(false, Frame::is_empty) && frames.first().is_some_and(Frame::is_empty)
{ {
// Remove existing footnotes attempts because we need to // Remove existing footnotes attempts because we need to
// move the item to the next page. // move the item to the next page.

View File

@ -78,7 +78,7 @@ pub(super) fn breakpoints<'a>(
let (link, _) = link_prefix(tail); let (link, _) = link_prefix(tail);
let end = last + link.len(); let end = last + link.len();
linebreak_link(link, |i| f(last + i, Breakpoint::Normal)); linebreak_link(link, |i| f(last + i, Breakpoint::Normal));
while iter.peek().map_or(false, |&p| p < end) { while iter.peek().is_some_and(|&p| p < end) {
iter.next(); iter.next();
} }
} }

View File

@ -655,7 +655,7 @@ fn add_cjk_latin_spacing(items: &mut [Item]) {
}); });
// Case 1: CJ followed by a Latin character // Case 1: CJ followed by a Latin character
if glyph.is_cj_script() && next.map_or(false, |g| g.is_letter_or_number()) { if glyph.is_cj_script() && next.is_some_and(|g| g.is_letter_or_number()) {
// The spacing is default to 1/4 em, and can be shrunk to 1/8 em. // The spacing is default to 1/4 em, and can be shrunk to 1/8 em.
glyph.x_advance += Em::new(0.25); glyph.x_advance += Em::new(0.25);
glyph.adjustability.shrinkability.1 += Em::new(0.125); glyph.adjustability.shrinkability.1 += Em::new(0.125);
@ -663,7 +663,7 @@ fn add_cjk_latin_spacing(items: &mut [Item]) {
} }
// Case 2: Latin followed by a CJ character // Case 2: Latin followed by a CJ character
if glyph.is_cj_script() && prev.map_or(false, |g| g.is_letter_or_number()) { if glyph.is_cj_script() && prev.is_some_and(|g| g.is_letter_or_number()) {
glyph.x_advance += Em::new(0.25); glyph.x_advance += Em::new(0.25);
glyph.x_offset += Em::new(0.25); glyph.x_offset += Em::new(0.25);
glyph.adjustability.shrinkability.0 += Em::new(0.125); glyph.adjustability.shrinkability.0 += Em::new(0.125);
@ -1374,7 +1374,7 @@ fn reorder<'a>(line: &'a Line<'a>) -> (Vec<&Item<'a>>, bool) {
// Compute the reordered ranges in visual order (left to right). // Compute the reordered ranges in visual order (left to right).
let (levels, runs) = line.bidi.visual_runs(para, line.trimmed.clone()); let (levels, runs) = line.bidi.visual_runs(para, line.trimmed.clone());
let starts_rtl = levels.first().map_or(false, |level| level.is_rtl()); let starts_rtl = levels.first().is_some_and(|level| level.is_rtl());
// Collect the reordered items. // Collect the reordered items.
for run in runs { for run in runs {

View File

@ -680,7 +680,7 @@ fn shape_segment<'a>(
let mut buffer = UnicodeBuffer::new(); let mut buffer = UnicodeBuffer::new();
buffer.push_str(text); buffer.push_str(text);
buffer.set_language(language(ctx.styles)); buffer.set_language(language(ctx.styles));
if let Some(script) = TextElem::script_in(ctx.styles).as_custom().and_then(|script| { if let Some(script) = TextElem::script_in(ctx.styles).custom().and_then(|script| {
rustybuzz::Script::from_iso15924_tag(Tag::from_bytes(script.as_bytes())) rustybuzz::Script::from_iso15924_tag(Tag::from_bytes(script.as_bytes()))
}) { }) {
buffer.set_script(script) buffer.set_script(script)
@ -751,7 +751,7 @@ fn shape_segment<'a>(
} else { } else {
// First, search for the end of the tofu sequence. // First, search for the end of the tofu sequence.
let k = i; let k = i;
while infos.get(i + 1).map_or(false, |info| info.glyph_id == 0) { while infos.get(i + 1).is_some_and(|info| info.glyph_id == 0) {
i += 1; i += 1;
} }
@ -781,7 +781,7 @@ fn shape_segment<'a>(
// Trim half-baked cluster. // Trim half-baked cluster.
let remove = base + start..base + end; let remove = base + start..base + end;
while ctx.glyphs.last().map_or(false, |g| remove.contains(&g.range.start)) { while ctx.glyphs.last().is_some_and(|g| remove.contains(&g.range.start)) {
ctx.glyphs.pop(); ctx.glyphs.pop();
} }
@ -866,7 +866,7 @@ fn track_and_space(ctx: &mut ShapingContext) {
if glyphs if glyphs
.peek() .peek()
.map_or(false, |next| glyph.range.start != next.range.start) .is_some_and(|next| glyph.range.start != next.range.start)
{ {
glyph.x_advance += tracking; glyph.x_advance += tracking;
} }

View File

@ -360,7 +360,7 @@ impl Packed<PageElem> {
let two_sided = margin.two_sided.unwrap_or(false); let two_sided = margin.two_sided.unwrap_or(false);
let margin = margin let margin = margin
.sides .sides
.map(|side| side.and_then(Smart::as_custom).unwrap_or(default)) .map(|side| side.and_then(Smart::custom).unwrap_or(default))
.resolve(styles) .resolve(styles)
.relative_to(size); .relative_to(size);

View File

@ -101,7 +101,7 @@ impl Packed<PlaceElem> {
let alignment = self.alignment(styles); let alignment = self.alignment(styles);
if float if float
&& alignment.map_or(false, |align| { && alignment.is_custom_and(|align| {
matches!(align.y(), None | Some(VAlignment::Horizon)) matches!(align.y(), None | Some(VAlignment::Horizon))
}) })
{ {

View File

@ -31,8 +31,7 @@ pub(super) fn spacing(
let width = size_ref.font_size().map_or(Abs::zero(), |size| v.at(size)); let width = size_ref.font_size().map_or(Abs::zero(), |size| v.at(size));
Some(SpacingFragment { width, weak: false }.into()) Some(SpacingFragment { width, weak: false }.into())
}; };
let script = let script = |f: &MathFragment| f.math_size().is_some_and(|s| s <= MathSize::Script);
|f: &MathFragment| f.math_size().map_or(false, |s| s <= MathSize::Script);
match (l.class(), r.class()) { match (l.class(), r.class()) {
// No spacing before punctuation; thin spacing after punctuation, unless // No spacing before punctuation; thin spacing after punctuation, unless

View File

@ -779,7 +779,7 @@ impl<'a> Generator<'a> {
let citations = self.display_citations(rendered); let citations = self.display_citations(rendered);
let references = self.display_references(rendered); let references = self.display_references(rendered);
let hanging_indent = let hanging_indent =
rendered.bibliography.as_ref().map_or(false, |b| b.hanging_indent); rendered.bibliography.as_ref().is_some_and(|b| b.hanging_indent);
Ok(Works { citations, references, hanging_indent }) Ok(Works { citations, references, hanging_indent })
} }

View File

@ -231,7 +231,7 @@ impl Show for Packed<OutlineElem> {
while ancestors while ancestors
.last() .last()
.and_then(|ancestor| ancestor.with::<dyn Outlinable>()) .and_then(|ancestor| ancestor.with::<dyn Outlinable>())
.map_or(false, |last| last.level() >= *level) .is_some_and(|last| last.level() >= *level)
{ {
ancestors.pop(); ancestors.pop();
} }

View File

@ -153,7 +153,7 @@ impl<'a> BehavedBuilder<'a> {
// Store a suffix map for the next element if it has the same style // Store a suffix map for the next element if it has the same style
// chain. // chain.
if iter.peek().map_or(false, |&(_, s2)| s == s2) { if iter.peek().is_some_and(|&(_, s2)| s == s2) {
reuse = Some(suffix.clone()); reuse = Some(suffix.clone());
} }

View File

@ -161,7 +161,7 @@ impl<'a, 'v, 't> Builder<'a, 'v, 't> {
let keep = content let keep = content
.to_packed::<PagebreakElem>() .to_packed::<PagebreakElem>()
.map_or(false, |pagebreak| !pagebreak.weak(styles)); .is_some_and(|pagebreak| !pagebreak.weak(styles));
self.interrupt_page(keep.then_some(styles), false)?; self.interrupt_page(keep.then_some(styles), false)?;
@ -427,7 +427,7 @@ impl<'a> ParBuilder<'a> {
|| content.is::<SmartQuoteElem>() || content.is::<SmartQuoteElem>()
|| content || content
.to_packed::<EquationElem>() .to_packed::<EquationElem>()
.map_or(false, |elem| !elem.block(styles)) .is_some_and(|elem| !elem.block(styles))
|| content.is::<BoxElem>() || content.is::<BoxElem>()
{ {
self.0.push(content, styles); self.0.push(content, styles);

View File

@ -439,7 +439,7 @@ pub(crate) fn decorate(
// Only do the costly segments intersection test if the line // Only do the costly segments intersection test if the line
// intersects the bounding box. // intersects the bounding box.
let intersect = bbox.map_or(false, |bbox| { let intersect = bbox.is_some_and(|bbox| {
let y_min = -text.font.to_em(bbox.y_max).at(text.size); let y_min = -text.font.to_em(bbox.y_max).at(text.size);
let y_max = -text.font.to_em(bbox.y_min).at(text.size); let y_max = -text.font.to_em(bbox.y_min).at(text.size);
offset >= y_min && offset <= y_max offset >= y_min && offset <= y_max

View File

@ -952,7 +952,7 @@ cast! {
TextDir, TextDir,
self => self.0.into_value(), self => self.0.into_value(),
v: Smart<Dir> => { v: Smart<Dir> => {
if v.map_or(false, |dir| dir.axis() == Axis::Y) { if v.is_custom_and(|dir| dir.axis() == Axis::Y) {
bail!("text direction must be horizontal"); bail!("text direction must be horizontal");
} }
Self(v) Self(v)

View File

@ -152,7 +152,7 @@ pub fn option_eq<L, R>(left: Option<L>, other: R) -> bool
where where
L: PartialEq<R>, L: PartialEq<R>,
{ {
left.map_or(false, |v| v == other) left.is_some_and(|v| v == other)
} }
/// A container around a static reference that is cheap to clone and hash. /// A container around a static reference that is cheap to clone and hash.

View File

@ -351,7 +351,7 @@ fn func_model(
let mut self_ = false; let mut self_ = false;
let mut params = func.params().unwrap(); let mut params = func.params().unwrap();
if params.first().map_or(false, |first| first.name == "self") { if params.first().is_some_and(|first| first.name == "self") {
self_ = true; self_ = true;
params = &params[1..]; params = &params[1..];
} }

View File

@ -95,7 +95,7 @@ fn resolve_definition(head: &str, base: &str) -> StrResult<String> {
} else if value } else if value
.clone() .clone()
.cast::<Func>() .cast::<Func>()
.map_or(false, |func| func.param(next).is_some()) .is_ok_and(|func| func.param(next).is_some())
{ {
route.push_str("#parameters-"); route.push_str("#parameters-");
route.push_str(next); route.push_str(next);

View File

@ -805,7 +805,7 @@ fn test_diagnostics<'a>(
let mut actual_diagnostics = HashSet::new(); let mut actual_diagnostics = HashSet::new();
for diagnostic in diagnostics { for diagnostic in diagnostics {
// Ignore diagnostics from other files. // Ignore diagnostics from other files.
if diagnostic.span.id().map_or(false, |id| id != source.id()) { if diagnostic.span.id().is_some_and(|id| id != source.id()) {
continue; continue;
} }