Skip to content

Commit

Permalink
Misc clippy fixes (#872)
Browse files Browse the repository at this point in the history
* `clippy::bool_assert_comparison`
* `clippy::field_reassign_with_default`
* `clippy::legacy_numeric_constants`
* `clippy::manual_clamp`
* `clippy::map_flatten`
* `clippy::needless_borrows_for_generic_args`
* `clippy::needless_lifetimes`
* `clippy::redundant_field_names`
* `clippy::to_string_in_format_args`
* `clippy::unnecessary_cast`
* `clippy::useless_format`
  • Loading branch information
waywardmonkeys authored Dec 25, 2024
1 parent bf454cc commit 6df6351
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 74 deletions.
2 changes: 1 addition & 1 deletion crates/c-api/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ pub extern "C" fn resvg_options_set_resources_dir(opt: *mut resvg_options, path:
/// Default: 96
#[no_mangle]
pub extern "C" fn resvg_options_set_dpi(opt: *mut resvg_options, dpi: f32) {
cast_opt(opt).dpi = dpi as f32;
cast_opt(opt).dpi = dpi;
}

/// @brief Sets the default font family.
Expand Down
18 changes: 11 additions & 7 deletions crates/resvg/examples/draw_bboxes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ fn main() {
1.0
};

let mut opt = usvg::Options::default();
// Get file's absolute directory.
opt.resources_dir = std::fs::canonicalize(&args[1])
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf()));
let mut opt = usvg::Options {
// Get file's absolute directory.
resources_dir: std::fs::canonicalize(&args[1])
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf())),
..usvg::Options::default()
};

opt.fontdb_mut().load_system_fonts();

Expand All @@ -38,8 +40,10 @@ fn main() {
let render_ts = tiny_skia::Transform::from_scale(zoom, zoom);
resvg::render(&tree, render_ts, &mut pixmap.as_mut());

let mut stroke = tiny_skia::Stroke::default();
stroke.width = 1.0 / zoom; // prevent stroke scaling as well
let stroke = tiny_skia::Stroke {
width: 1.0 / zoom, // prevent stroke scaling as well
..tiny_skia::Stroke::default()
};

let mut paint1 = tiny_skia::Paint::default();
paint1.set_color_rgba8(255, 0, 0, 127);
Expand Down
13 changes: 7 additions & 6 deletions crates/resvg/examples/minimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ fn main() {
}

let tree = {
let mut opt = usvg::Options::default();
// Get file's absolute directory.
opt.resources_dir = std::fs::canonicalize(&args[1])
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf()));

let mut opt = usvg::Options {
// Get file's absolute directory.
resources_dir: std::fs::canonicalize(&args[1])
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf())),
..usvg::Options::default()
};
opt.fontdb_mut().load_system_fonts();

let svg_data = std::fs::read(&args[1]).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/resvg/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ fn parse_args() -> Result<Args, String> {

let style_sheet = match args.style_sheet.as_ref() {
Some(p) => Some(
std::fs::read(&p)
std::fs::read(p)
.ok()
.and_then(|s| std::str::from_utf8(&s).ok().map(|s| s.to_string()))
.ok_or("failed to read stylesheet".to_string())?,
Expand Down
30 changes: 18 additions & 12 deletions crates/resvg/tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,16 @@ pub fn render(name: &str) -> usize {
let svg_path = format!("tests/{}.svg", name);
let png_path = format!("tests/{}.png", name);

let mut opt = usvg::Options::default();
opt.resources_dir = Some(
std::path::PathBuf::from(&svg_path)
.parent()
.unwrap()
.to_owned(),
);
opt.fontdb = GLOBAL_FONTDB.clone();
let opt = usvg::Options {
resources_dir: Some(
std::path::PathBuf::from(&svg_path)
.parent()
.unwrap()
.to_owned(),
),
fontdb: GLOBAL_FONTDB.clone(),
..usvg::Options::default()
};

let tree = {
let svg_data = std::fs::read(&svg_path).unwrap();
Expand Down Expand Up @@ -98,8 +100,10 @@ pub fn render_extra_with_scale(name: &str, scale: f32) -> usize {
let svg_path = format!("tests/{}.svg", name);
let png_path = format!("tests/{}.png", name);

let mut opt = usvg::Options::default();
opt.fontdb = GLOBAL_FONTDB.clone();
let opt = usvg::Options {
fontdb: GLOBAL_FONTDB.clone(),
..usvg::Options::default()
};

let tree = {
let svg_data = std::fs::read(&svg_path).unwrap();
Expand Down Expand Up @@ -148,8 +152,10 @@ pub fn render_node(name: &str, id: &str) -> usize {
let svg_path = format!("tests/{}.svg", name);
let png_path = format!("tests/{}.png", name);

let mut opt = usvg::Options::default();
opt.fontdb = GLOBAL_FONTDB.clone();
let opt = usvg::Options {
fontdb: GLOBAL_FONTDB.clone(),
..usvg::Options::default()
};

let tree = {
let svg_data = std::fs::read(&svg_path).unwrap();
Expand Down
12 changes: 6 additions & 6 deletions crates/usvg/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ fn main() {
}

if let Err(e) = process(args) {
eprintln!("Error: {}.", e.to_string());
eprintln!("Error: {}.", e);
process::exit(1);
}
}
Expand All @@ -326,7 +326,7 @@ fn process(args: Args) -> Result<(), String> {
let svg_from = if in_svg == "-" {
InputFrom::Stdin
} else if in_svg == "-c" {
return Err(format!("-c should be set after input"));
return Err("-c should be set after input".to_string());
} else {
InputFrom::File(in_svg)
};
Expand Down Expand Up @@ -456,13 +456,13 @@ fn process(args: Args) -> Result<(), String> {
OutputTo::Stdout => {
io::stdout()
.write_all(s.as_bytes())
.map_err(|_| format!("failed to write to the stdout"))?;
.map_err(|_| "failed to write to the stdout".to_string())?;
}
OutputTo::File(path) => {
let mut f =
File::create(path).map_err(|_| format!("failed to create the output file"))?;
File::create(path).map_err(|_| "failed to create the output file".to_string())?;
f.write_all(s.as_bytes())
.map_err(|_| format!("failed to write to the output file"))?;
.map_err(|_| "failed to write to the output file".to_string())?;
}
}

Expand All @@ -476,7 +476,7 @@ fn load_stdin() -> Result<Vec<u8>, String> {

handle
.read_to_end(&mut buf)
.map_err(|_| format!("failed to read from stdin"))?;
.map_err(|_| "failed to read from stdin".to_string())?;

Ok(buf)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/usvg/src/parser/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub(crate) fn convert(
id: cache.gen_filter_id(),
rect,
primitives: vec![Primitive {
rect: rect,
rect,
// Unlike `filter` elements, filter functions use sRGB colors by default.
color_interpolation: ColorInterpolation::SRGB,
result: "result".to_string(),
Expand Down Expand Up @@ -800,8 +800,8 @@ fn convert_std_dev_attr(fe: SvgNode, scale: Size, default: &str) -> (PositiveF32
let std_dev_x = (std_dev_x as f32) * scale.width();
let std_dev_y = (std_dev_y as f32) * scale.height();

let std_dev_x = PositiveF32::new(std_dev_x as f32).unwrap_or(PositiveF32::ZERO);
let std_dev_y = PositiveF32::new(std_dev_y as f32).unwrap_or(PositiveF32::ZERO);
let std_dev_x = PositiveF32::new(std_dev_x).unwrap_or(PositiveF32::ZERO);
let std_dev_y = PositiveF32::new(std_dev_y).unwrap_or(PositiveF32::ZERO);

(std_dev_x, std_dev_y)
}
Expand Down
46 changes: 22 additions & 24 deletions crates/usvg/src/parser/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,37 +328,35 @@ fn get_image_data_format(data: &[u8]) -> Option<ImageFormat> {
/// Unlike `Tree::from_*` methods, this one will also remove all `image` elements
/// from the loaded SVG, as required by the spec.
pub(crate) fn load_sub_svg(data: &[u8], opt: &Options) -> Option<ImageKind> {
let mut sub_opt = Options::default();
sub_opt.resources_dir = None;
sub_opt.dpi = opt.dpi;
sub_opt.font_size = opt.font_size;
sub_opt.languages = opt.languages.clone();
sub_opt.shape_rendering = opt.shape_rendering;
sub_opt.text_rendering = opt.text_rendering;
sub_opt.image_rendering = opt.image_rendering;
sub_opt.default_size = opt.default_size;

// The referenced SVG image cannot have any 'image' elements by itself.
// Not only recursive. Any. Don't know why.
sub_opt.image_href_resolver = ImageHrefResolver {
resolve_data: Box::new(|_, _, _| None),
resolve_string: Box::new(|_, _| None),
};

#[cfg(feature = "text")]
{
let sub_opt = Options {
resources_dir: None,
dpi: opt.dpi,
font_size: opt.font_size,
languages: opt.languages.clone(),
shape_rendering: opt.shape_rendering,
text_rendering: opt.text_rendering,
image_rendering: opt.image_rendering,
default_size: opt.default_size,
// The referenced SVG image cannot have any 'image' elements by itself.
// Not only recursive. Any. Don't know why.
image_href_resolver: ImageHrefResolver {
resolve_data: Box::new(|_, _, _| None),
resolve_string: Box::new(|_, _| None),
},
// In the referenced SVG, we start with the unmodified user-provided
// fontdb, not the one from the cache.
sub_opt.fontdb = opt.fontdb.clone();

#[cfg(feature = "text")]
fontdb: opt.fontdb.clone(),
// Can't clone the resolver, so we create a new one that forwards to it.
sub_opt.font_resolver = crate::FontResolver {
#[cfg(feature = "text")]
font_resolver: crate::FontResolver {
select_font: Box::new(|font, db| (opt.font_resolver.select_font)(font, db)),
select_fallback: Box::new(|c, used_fonts, db| {
(opt.font_resolver.select_fallback)(c, used_fonts, db)
}),
};
}
},
..Options::default()
};

let tree = Tree::from_data(data, &sub_opt);
let tree = match tree {
Expand Down
6 changes: 2 additions & 4 deletions crates/usvg/src/parser/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,14 +160,12 @@ fn convert_paint(
svgtypes::Paint::ContextFill => state
.context_element
.clone()
.map(|(f, _)| f)
.flatten()
.and_then(|(f, _)| f)
.map(|f| (f.paint, f.context_element)),
svgtypes::Paint::ContextStroke => state
.context_element
.clone()
.map(|(_, s)| s)
.flatten()
.and_then(|(_, s)| s)
.map(|s| (s.paint, s.context_element)),
svgtypes::Paint::CurrentColor => {
let svg_color: svgtypes::Color = node
Expand Down
4 changes: 2 additions & 2 deletions crates/usvg/src/parser/svgtree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ pub(crate) struct NodeId(NonZeroU32);
impl NodeId {
#[inline]
fn new(id: u32) -> Self {
debug_assert!(id < core::u32::MAX);
debug_assert!(id < u32::MAX);

// We are using `NonZeroU32` to reduce overhead of `Option<NodeId>`.
NodeId(NonZeroU32::new(id + 1).unwrap())
Expand All @@ -176,7 +176,7 @@ impl From<usize> for NodeId {
#[inline]
fn from(id: usize) -> Self {
// We already checked that `id` is limited by u32::MAX.
debug_assert!(id <= core::u32::MAX as usize);
debug_assert!(id <= u32::MAX as usize);
NodeId::new(id as u32)
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/usvg/src/text/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ fn collect_normals(
let mut offset = curve.inv_arclen(offset - length, arclen_accuracy as f64);
// some rounding error may occur, so we give offset a little tolerance
debug_assert!((-1.0e-3..=1.0 + 1.0e-3).contains(&offset));
offset = offset.min(1.0).max(0.0);
offset = offset.clamp(0.0, 1.0);

let pos = curve.eval(offset);
let d = curve.deriv().eval(offset);
Expand Down Expand Up @@ -1448,7 +1448,7 @@ impl<'a> GlyphClusters<'a> {
}
}

impl<'a> Iterator for GlyphClusters<'a> {
impl Iterator for GlyphClusters<'_> {
type Item = (std::ops::Range<usize>, ByteIndex);

fn next(&mut self) -> Option<Self::Item> {
Expand Down
2 changes: 1 addition & 1 deletion crates/usvg/tests/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn clippath_with_invalid_child() {

let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
// clipPath is invalid and should be removed together with rect.
assert_eq!(tree.root().has_children(), false);
assert!(!tree.root().has_children());
}

#[test]
Expand Down
12 changes: 7 additions & 5 deletions crates/usvg/tests/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@ fn resave_impl(name: &str, id_prefix: Option<String>, preserve_text: bool) {
};
usvg::Tree::from_str(&input_svg, &opt).unwrap()
};
let mut xml_opt = usvg::WriteOptions::default();
xml_opt.id_prefix = id_prefix;
xml_opt.preserve_text = preserve_text;
xml_opt.coordinates_precision = 4; // Reduce noise and file size.
xml_opt.transforms_precision = 4;
let xml_opt = usvg::WriteOptions {
id_prefix,
preserve_text,
coordinates_precision: 4, // Reduce noise and file size.
transforms_precision: 4,
..usvg::WriteOptions::default()
};
let output_svg = tree.to_string(&xml_opt);

// std::fs::write(
Expand Down

0 comments on commit 6df6351

Please sign in to comment.