clippy: Fix warnings in shared and config, fonts, layout, and layout_2020 components (#32674)

This commit is contained in:
Martin Robinson 2024-07-04 16:18:58 +02:00 committed by GitHub
parent 99c1f886b8
commit 4b63043c6a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 72 additions and 78 deletions

View file

@ -3,7 +3,6 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt; use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use std::sync::RwLock; use std::sync::RwLock;
@ -158,10 +157,7 @@ impl From<PrefValue> for [f64; 4] {
fn from(other: PrefValue) -> [f64; 4] { fn from(other: PrefValue) -> [f64; 4] {
match other { match other {
PrefValue::Array(values) if values.len() == 4 => { PrefValue::Array(values) if values.len() == 4 => {
let f = values let f = values.into_iter().map(Into::into).collect::<Vec<f64>>();
.into_iter()
.filter_map(|v| v.try_into().ok())
.collect::<Vec<f64>>();
if f.len() == 4 { if f.len() == 4 {
[f[0], f[1], f[2], f[3]] [f[0], f[1], f[2], f[3]]
} else { } else {

View file

@ -329,8 +329,7 @@ impl Font {
} }
} }
let is_single_preserved_newline = text.len() == 1 && text.chars().next() == Some('\n'); let is_single_preserved_newline = text.len() == 1 && text.starts_with('\n');
let start_time = Instant::now(); let start_time = Instant::now();
let mut glyphs = GlyphStore::new( let mut glyphs = GlyphStore::new(
text.len(), text.len(),

View file

@ -2,7 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::convert::TryInto;
use std::os::raw::c_long; use std::os::raw::c_long;
use std::sync::Arc; use std::sync::Arc;
use std::{mem, ptr}; use std::{mem, ptr};
@ -106,12 +105,11 @@ fn create_face(data: Arc<Vec<u8>>, face_index: u32) -> Result<FT_Face, &'static
let library = FreeTypeLibraryHandle::get().lock(); let library = FreeTypeLibraryHandle::get().lock();
// This is to support 32bit Android where FT_Long is defined as i32. // This is to support 32bit Android where FT_Long is defined as i32.
let face_index = face_index.try_into().unwrap();
let result = FT_New_Memory_Face( let result = FT_New_Memory_Face(
library.freetype_library, library.freetype_library,
data.as_ptr(), data.as_ptr(),
data.len() as FT_Long, data.len() as FT_Long,
face_index, face_index as FT_Long,
&mut face, &mut face,
); );

View file

@ -109,7 +109,7 @@ impl DisplayList {
/// Return the bounds of this display list based on the dimensions of the root /// Return the bounds of this display list based on the dimensions of the root
/// stacking context. /// stacking context.
pub fn bounds(&self) -> LayoutRect { pub fn bounds(&self) -> LayoutRect {
match self.list.get(0) { match self.list.first() {
Some(DisplayItem::PushStackingContext(item)) => item.stacking_context.bounds, Some(DisplayItem::PushStackingContext(item)) => item.stacking_context.bounds,
Some(_) => unreachable!("Root element of display list not stacking context."), Some(_) => unreachable!("Root element of display list not stacking context."),
None => LayoutRect::zero(), None => LayoutRect::zero(),

View file

@ -74,8 +74,11 @@ use crate::table_wrapper::TableWrapperFlow;
/// This marker trait indicates that a type is a struct with `#[repr(C)]` whose first field /// This marker trait indicates that a type is a struct with `#[repr(C)]` whose first field
/// is of type `BaseFlow` or some type that also implements this trait. /// is of type `BaseFlow` or some type that also implements this trait.
/// ///
/// In other words, the memory representation of `BaseFlow` must be a prefix /// # Safety
/// of the memory representation of types implementing `HasBaseFlow`. ///
/// The memory representation of `BaseFlow` must be a prefix of the memory representation of types
/// implementing `HasBaseFlow`. If this isn't the case, calling [`GetBaseFlow::base`] or
/// [`GetBaseFlow::mut_base`] could lead to memory errors.
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe trait HasBaseFlow {} pub unsafe trait HasBaseFlow {}

View file

@ -18,7 +18,7 @@ use serde_json::{to_string, to_value, Value};
use crate::flow::GetBaseFlow; use crate::flow::GetBaseFlow;
use crate::flow_ref::FlowRef; use crate::flow_ref::FlowRef;
thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); thread_local!(static STATE_KEY: RefCell<Option<State>> = const { RefCell::new(None) });
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0); static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);

View file

@ -833,6 +833,7 @@ fn is_specific(script: Script) -> bool {
} }
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(clippy::enum_variant_names)]
pub enum CompressionMode { pub enum CompressionMode {
CompressNone, CompressNone,
CompressWhitespace, CompressWhitespace,

View file

@ -21,7 +21,7 @@ use xi_unicode::LineBreakLeafIter;
thread_local! { thread_local! {
static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, ByteIndex, usize)>> = static INDEX_OF_FIRST_GLYPH_RUN_CACHE: Cell<Option<(*const TextRun, ByteIndex, usize)>> =
Cell::new(None) const { Cell::new(None) }
} }
/// A single "paragraph" of text in one font size and style. /// A single "paragraph" of text in one font size and style.

View file

@ -187,8 +187,12 @@ where
fn process(&mut self, node: &ConcreteThreadSafeLayoutNode); fn process(&mut self, node: &ConcreteThreadSafeLayoutNode);
} }
#[allow(unsafe_code)] /// # Safety
///
/// This function modifies the DOM node represented by the `node` argument, so it is imperitive
/// that no other thread is modifying the node at the same time.
#[inline] #[inline]
#[allow(unsafe_code)]
pub unsafe fn construct_flows_at_ancestors<'dom>( pub unsafe fn construct_flows_at_ancestors<'dom>(
context: &LayoutContext, context: &LayoutContext,
mut node: impl LayoutNode<'dom>, mut node: impl LayoutNode<'dom>,

View file

@ -410,7 +410,7 @@ fn gradient_items_to_color_stops(
} }
/// <https://drafts.csswg.org/css-images-4/#color-stop-fixup> /// <https://drafts.csswg.org/css-images-4/#color-stop-fixup>
fn fixup_stops(stops: &mut Vec<ColorStop<ColorF, f32>>) -> Vec<wr::GradientStop> { fn fixup_stops(stops: &mut [ColorStop<ColorF, f32>]) -> Vec<wr::GradientStop> {
assert!(stops.len() >= 2); assert!(stops.len() >= 2);
// https://drafts.csswg.org/css-images-4/#color-stop-fixup // https://drafts.csswg.org/css-images-4/#color-stop-fixup

View file

@ -176,13 +176,11 @@ where
if self.type_id() != ScriptLayoutNodeType::Element(LayoutElementType::HTMLObjectElement) { if self.type_id() != ScriptLayoutNodeType::Element(LayoutElementType::HTMLObjectElement) {
return None; return None;
} }
let Some(element) = self.to_threadsafe().as_element() else {
return None;
};
// TODO: This is the what the legacy layout system does, but really if Servo // TODO: This is the what the legacy layout system does, but really if Servo
// supports any `<object>` that's an image, it should support those with URLs // supports any `<object>` that's an image, it should support those with URLs
// and `type` attributes with image mime types. // and `type` attributes with image mime types.
let element = self.to_threadsafe().as_element()?;
if element.get_attr(&ns!(), &local_name!("type")).is_some() { if element.get_attr(&ns!(), &local_name!("type")).is_some() {
return None; return None;
} }

View file

@ -156,14 +156,12 @@ where
.push_text(flex_text_run.text, &flex_text_run.info); .push_text(flex_text_run.text, &flex_text_run.info);
} }
let Some(inline_formatting_context) = inline_formatting_context_builder.finish( let inline_formatting_context = inline_formatting_context_builder.finish(
self.context, self.context,
self.text_decoration_line, self.text_decoration_line,
true, /* has_first_formatted_line */ true, /* has_first_formatted_line */
false, /* is_single_line_text_box */ false, /* is_single_line_text_box */
) else { )?;
return None;
};
let block_formatting_context = BlockFormattingContext::from_block_container( let block_formatting_context = BlockFormattingContext::from_block_container(
BlockContainer::InlineFormattingContext(inline_formatting_context), BlockContainer::InlineFormattingContext(inline_formatting_context),

View file

@ -3,6 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cell::Cell; use std::cell::Cell;
use std::cmp::Ordering;
use app_units::Au; use app_units::Au;
use atomic_refcell::AtomicRefMut; use atomic_refcell::AtomicRefMut;
@ -1111,40 +1112,44 @@ impl FlexLine<'_> {
// “Freeze over-flexed items.” // “Freeze over-flexed items.”
let total_violation: Au = unfrozen_items().map(violation).sum(); let total_violation: Au = unfrozen_items().map(violation).sum();
if total_violation == Au::zero() { match total_violation.cmp(&Au::zero()) {
// “Freeze all items.” Ordering::Equal => {
// Return instead, as thats what the next loop iteration would do. // “Freeze all items.”
let remaining_free_space = // Return instead, as thats what the next loop iteration would do.
container_main_size - target_main_sizes_vec.iter().cloned().sum(); let remaining_free_space =
return (target_main_sizes_vec, remaining_free_space); container_main_size - target_main_sizes_vec.iter().cloned().sum();
} else if total_violation > Au::zero() { return (target_main_sizes_vec, remaining_free_space);
// “Freeze all the items with min violations.” },
// “If the items target main size was made larger by [clamping], Ordering::Greater => {
// its a min violation.” // “Freeze all the items with min violations.”
for (item_and_target_main_size, frozen) in items() { // “If the items target main size was made larger by [clamping],
if violation(item_and_target_main_size) > Au::zero() { // its a min violation.”
let (item, target_main_size) = item_and_target_main_size; for (item_and_target_main_size, frozen) in items() {
target_main_size.set(item.content_min_size.main); if violation(item_and_target_main_size) > Au::zero() {
frozen_count.set(frozen_count.get() + 1); let (item, target_main_size) = item_and_target_main_size;
frozen.set(true); target_main_size.set(item.content_min_size.main);
frozen_count.set(frozen_count.get() + 1);
frozen.set(true);
}
} }
} },
} else { Ordering::Less => {
// Negative total violation // Negative total violation
// “Freeze all the items with max violations.” // “Freeze all the items with max violations.”
// “If the items target main size was made smaller by [clamping], // “If the items target main size was made smaller by [clamping],
// its a max violation.” // its a max violation.”
for (item_and_target_main_size, frozen) in items() { for (item_and_target_main_size, frozen) in items() {
if violation(item_and_target_main_size) < Au::zero() { if violation(item_and_target_main_size) < Au::zero() {
let (item, target_main_size) = item_and_target_main_size; let (item, target_main_size) = item_and_target_main_size;
let Some(max_size) = item.content_max_size.main else { let Some(max_size) = item.content_max_size.main else {
unreachable!() unreachable!()
}; };
target_main_size.set(max_size); target_main_size.set(max_size);
frozen_count.set(frozen_count.get() + 1); frozen_count.set(frozen_count.get() + 1);
frozen.set(true); frozen.set(true);
}
} }
} },
} }
} }
} }

View file

@ -605,11 +605,7 @@ where
if self.next_character.is_none() { if self.next_character.is_none() {
self.next_character = self.iterator.next(); self.next_character = self.iterator.next();
} }
let character = self.next_character?;
let Some(character) = self.next_character else {
return None;
};
self.next_character = self.iterator.next(); self.next_character = self.iterator.next();
Some((character, self.next_character)) Some((character, self.next_character))
} }

View file

@ -19,7 +19,7 @@ use serde_json::{to_string, to_value, Value};
use crate::flow::BoxTree; use crate::flow::BoxTree;
use crate::fragment_tree::FragmentTree; use crate::fragment_tree::FragmentTree;
thread_local!(static STATE_KEY: RefCell<Option<State>> = RefCell::new(None)); thread_local!(static STATE_KEY: RefCell<Option<State>> = const { RefCell::new(None) });
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0); static DEBUG_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);

View file

@ -575,10 +575,7 @@ fn try_to_parse_image_data_url(string: &str) -> Option<Url> {
if !string.starts_with("data:") { if !string.starts_with("data:") {
return None; return None;
} }
let Some(data_url) = DataUrl::process(string).ok() else { let data_url = DataUrl::process(string).ok()?;
return None;
};
let mime_type = data_url.mime_type(); let mime_type = data_url.mime_type();
if mime_type.type_ != "image" { if mime_type.type_ != "image" {
return None; return None;

View file

@ -2061,10 +2061,7 @@ impl<'a> TableLayout<'a> {
cell: &TableSlotCell, cell: &TableSlotCell,
coordinates: TableSlotCoordinates, coordinates: TableSlotCoordinates,
) -> Option<LogicalSides<Length>> { ) -> Option<LogicalSides<Length>> {
let Some(ref collapsed_borders) = self.collapsed_borders else { let collapsed_borders = self.collapsed_borders.as_ref()?;
return None;
};
let end_x = coordinates.x + cell.colspan; let end_x = coordinates.x + cell.colspan;
let end_y = coordinates.y + cell.rowspan; let end_y = coordinates.y + cell.rowspan;
let mut result: LogicalSides<Length> = LogicalSides { let mut result: LogicalSides<Length> = LogicalSides {

View file

@ -193,7 +193,7 @@ impl PipelineNamespace {
namespace_id_method! {next_blob_id, BlobId, self, BlobIndex} namespace_id_method! {next_blob_id, BlobId, self, BlobIndex}
} }
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None)); thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = const { Cell::new(None) });
#[derive( #[derive(
Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize, Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
@ -271,7 +271,8 @@ impl fmt::Display for BrowsingContextGroupId {
} }
} }
thread_local!(pub static TOP_LEVEL_BROWSING_CONTEXT_ID: Cell<Option<TopLevelBrowsingContextId>> = Cell::new(None)); thread_local!(pub static TOP_LEVEL_BROWSING_CONTEXT_ID: Cell<Option<TopLevelBrowsingContextId>> =
const { Cell::new(None) });
#[derive( #[derive(
Clone, Copy, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize, Clone, Copy, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,

View file

@ -4,6 +4,7 @@
#![deny(unsafe_code)] #![deny(unsafe_code)]
use std::fmt::Display;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use base::id::HistoryStateId; use base::id::HistoryStateId;
@ -118,9 +119,9 @@ pub enum ReferrerPolicy {
StrictOriginWhenCrossOrigin, StrictOriginWhenCrossOrigin,
} }
impl ToString for ReferrerPolicy { impl Display for ReferrerPolicy {
fn to_string(&self) -> String { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { let string = match self {
ReferrerPolicy::NoReferrer => "no-referrer", ReferrerPolicy::NoReferrer => "no-referrer",
ReferrerPolicy::NoReferrerWhenDowngrade => "no-referrer-when-downgrade", ReferrerPolicy::NoReferrerWhenDowngrade => "no-referrer-when-downgrade",
ReferrerPolicy::Origin => "origin", ReferrerPolicy::Origin => "origin",
@ -129,8 +130,8 @@ impl ToString for ReferrerPolicy {
ReferrerPolicy::UnsafeUrl => "unsafe-url", ReferrerPolicy::UnsafeUrl => "unsafe-url",
ReferrerPolicy::StrictOrigin => "strict-origin", ReferrerPolicy::StrictOrigin => "strict-origin",
ReferrerPolicy::StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin", ReferrerPolicy::StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin",
} };
.to_string() write!(formatter, "{string}")
} }
} }

View file

@ -79,7 +79,7 @@ unsafe impl Send for UntrustedNodeAddress {}
impl From<WebRenderUntrustedNodeAddress> for UntrustedNodeAddress { impl From<WebRenderUntrustedNodeAddress> for UntrustedNodeAddress {
fn from(o: WebRenderUntrustedNodeAddress) -> Self { fn from(o: WebRenderUntrustedNodeAddress) -> Self {
UntrustedNodeAddress(o.0 as *const c_void) UntrustedNodeAddress(o.0)
} }
} }