Skip to content

Commit

Permalink
Merge pull request #1636 from fintelia/rustfmt
Browse files Browse the repository at this point in the history
Run rustfmt and enforce via CI
  • Loading branch information
fintelia authored Dec 4, 2021
2 parents c20b3ee + afca279 commit 183e74e
Show file tree
Hide file tree
Showing 62 changed files with 4,337 additions and 2,112 deletions.
14 changes: 14 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,17 @@ jobs:
override: true
- name: build
run: cargo build -v --benches --features=benchmarks
rustfmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: rustfmt
- name: Run rustfmt check
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check
2 changes: 1 addition & 1 deletion benches/copy_from.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use image::{GenericImage, ImageBuffer, Rgba};
use criterion::{black_box, Criterion, criterion_group, criterion_main};

pub fn bench_copy_from(c: &mut Criterion) {
let src = ImageBuffer::from_pixel(2048, 2048, Rgba([255u8, 0, 0, 255]));
Expand Down
36 changes: 11 additions & 25 deletions benches/decode.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{iter, fs, path};
use std::{fs, iter, path};

use criterion::{criterion_group, criterion_main, Criterion};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};

#[derive(Clone, Copy)]
struct BenchDef {
Expand Down Expand Up @@ -30,18 +30,12 @@ fn load_all(c: &mut Criterion) {
},
BenchDef {
dir: &["gif", "simple"],
files: &[
"alpha_gif_a.gif",
"sample_1.gif",
],
files: &["alpha_gif_a.gif", "sample_1.gif"],
format: ImageFormat::Gif,
},
BenchDef {
dir: &["hdr", "images"],
files: &[
"image1.hdr",
"rgbr4x4.hdr",
],
files: &["image1.hdr", "rgbr4x4.hdr"],
format: ImageFormat::Hdr,
},
BenchDef {
Expand All @@ -56,23 +50,14 @@ fn load_all(c: &mut Criterion) {
},
BenchDef {
dir: &["jpg", "progressive"],
files: &[
"3.jpg",
"cat.jpg",
"test.jpg",
],
files: &["3.jpg", "cat.jpg", "test.jpg"],
format: ImageFormat::Jpeg,
},
// TODO: pnm
// TODO: png
BenchDef {
dir: &["tga", "testsuite"],
files: &[
"cbw8.tga",
"ctc24.tga",
"ubw8.tga",
"utc24.tga",
],
files: &["cbw8.tga", "ctc24.tga", "ubw8.tga", "utc24.tga"],
format: ImageFormat::Tga,
},
BenchDef {
Expand Down Expand Up @@ -113,11 +98,12 @@ fn bench_load(c: &mut Criterion, def: &BenchDef) {
for file_name in def.files {
let path: path::PathBuf = paths.clone().chain(iter::once(file_name)).collect();
let buf = fs::read(path).unwrap();
group.bench_function(file_name.to_owned(), |b| b.iter(|| {
image::load_from_memory_with_format(&buf, def.format).unwrap();
}));
group.bench_function(file_name.to_owned(), |b| {
b.iter(|| {
image::load_from_memory_with_format(&buf, def.format).unwrap();
})
});
}
}

const IMAGE_DIR: [&'static str; 3] = [".", "tests", "images"];

46 changes: 29 additions & 17 deletions benches/encode.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
extern crate criterion;

use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use image::{ColorType, codecs::bmp::BmpEncoder, codecs::jpeg::JpegEncoder};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use image::{codecs::bmp::BmpEncoder, codecs::jpeg::JpegEncoder, ColorType};

use std::fs::File;
use std::io::{BufWriter, Write, Seek, SeekFrom};
use std::io::{BufWriter, Seek, SeekFrom, Write};

trait Encoder {
fn encode_raw(&self, into: &mut Vec<u8>, im: &[u8], dims: u32, color: ColorType);
Expand Down Expand Up @@ -54,20 +54,32 @@ fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: C
let bytes = size as usize * usize::from(color.bytes_per_pixel());
let im = vec![0; bytes * bytes];

group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-rawvec", color), size), &im, |b, image| {
let mut v = vec![];
with.encode_raw(&mut v, &im, size, color);
b.iter(|| with.encode_raw(&mut v, image, size, color));
});
group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-bufvec", color), size), &im, |b, image| {
let mut v = vec![];
with.encode_raw(&mut v, &im, size, color);
b.iter(|| with.encode_bufvec(&mut v, image, size, color));
});
group.bench_with_input(BenchmarkId::new(format!("zero-{:?}-file", color), size), &im, |b, image| {
let file = File::create("temp.bmp").unwrap();
b.iter(|| with.encode_file(&file, image, size, color));
});
group.bench_with_input(
BenchmarkId::new(format!("zero-{:?}-rawvec", color), size),
&im,
|b, image| {
let mut v = vec![];
with.encode_raw(&mut v, &im, size, color);
b.iter(|| with.encode_raw(&mut v, image, size, color));
},
);
group.bench_with_input(
BenchmarkId::new(format!("zero-{:?}-bufvec", color), size),
&im,
|b, image| {
let mut v = vec![];
with.encode_raw(&mut v, &im, size, color);
b.iter(|| with.encode_bufvec(&mut v, image, size, color));
},
);
group.bench_with_input(
BenchmarkId::new(format!("zero-{:?}-file", color), size),
&im,
|b, image| {
let file = File::create("temp.bmp").unwrap();
b.iter(|| with.encode_file(&file, image, size, color));
},
);
}

fn encode_definition(criterion: &mut Criterion, def: &BenchDef) {
Expand Down
2 changes: 0 additions & 2 deletions examples/concat/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


use image::{GenericImage, GenericImageView, ImageBuffer, Pixel, Primitive};

/// Example showcasing a generic implementation of image concatenation.
Expand Down
5 changes: 4 additions & 1 deletion examples/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use std::path::Path;

fn main() {
let (from, into) = if env::args_os().count() == 3 {
(env::args_os().nth(1).unwrap(), env::args_os().nth(2).unwrap())
(
env::args_os().nth(1).unwrap(),
env::args_os().nth(2).unwrap(),
)
} else {
println!("Please enter a from and into path.");
std::process::exit(1);
Expand Down
2 changes: 1 addition & 1 deletion examples/gradient/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use image::{Rgba, RgbaImage, Pixel};
use image::{Pixel, Rgba, RgbaImage};

fn main() {
let mut img = RgbaImage::new(100, 100);
Expand Down
2 changes: 1 addition & 1 deletion examples/opening.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::env;
use std::fs::File;
use std::path::Path;

use image::{ImageFormat, GenericImageView};
use image::{GenericImageView, ImageFormat};

fn main() {
let file = if env::args().count() == 2 {
Expand Down
7 changes: 3 additions & 4 deletions examples/scaledown/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@


use image::ImageFormat;
use image::imageops::FilterType;
use image::ImageFormat;
use std::fmt;
use std::fs::File;
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -34,7 +32,8 @@ fn main() {
("cmr", FilterType::CatmullRom),
("gauss", FilterType::Gaussian),
("lcz2", FilterType::Lanczos3),
].iter()
]
.iter()
{
let timer = Instant::now();
let scaled = img.resize(400, 400, filter);
Expand Down
7 changes: 3 additions & 4 deletions examples/scaleup/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@


use image::ImageFormat;
use image::imageops::FilterType;
use image::ImageFormat;
use std::fmt;
use std::fs::File;
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -34,7 +32,8 @@ fn main() {
("xcmr", FilterType::CatmullRom),
("ygauss", FilterType::Gaussian),
("zlcz2", FilterType::Lanczos3),
].iter()
]
.iter()
{
let timer = Instant::now();
let scaled = tiny.resize(32, 32, filter);
Expand Down
33 changes: 20 additions & 13 deletions src/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use std::time::Duration;

use num_rational::Ratio;

use crate::RgbaImage;
use crate::error::ImageResult;
use crate::RgbaImage;

/// An implementation dependent iterator, reading the frames as requested
pub struct Frames<'a> {
iterator: Box<dyn Iterator<Item = ImageResult<Frame>> + 'a>
iterator: Box<dyn Iterator<Item = ImageResult<Frame>> + 'a>,
}

impl<'a> Frames<'a> {
Expand Down Expand Up @@ -114,7 +114,9 @@ impl Delay {
/// let delay_10ms = Delay::from_numer_denom_ms(10, 1);
/// ```
pub fn from_numer_denom_ms(numerator: u32, denominator: u32) -> Self {
Delay { ratio: Ratio::new_raw(numerator, denominator) }
Delay {
ratio: Ratio::new_raw(numerator, denominator),
}
}

/// Convert from a duration, clamped between 0 and an implemented defined maximum.
Expand Down Expand Up @@ -146,14 +148,14 @@ impl Delay {
let submillis = (duration.as_nanos() % 1_000_000) as u32;

let max_b = if millis > 0 {
((MILLIS_BOUND + 1)/(millis + 1)) as u32
((MILLIS_BOUND + 1) / (millis + 1)) as u32
} else {
MILLIS_BOUND as u32
};
let millis = millis as u32;

let (a, b) = Self::closest_bounded_fraction(max_b, submillis, 1_000_000);
Self::from_numer_denom_ms(a + b*millis, b)
Self::from_numer_denom_ms(a + b * millis, b)
}

/// The numerator and denominator of the delay in milliseconds.
Expand Down Expand Up @@ -188,13 +190,13 @@ impl Delay {

// Compare two fractions whose parts fit into a u32.
fn compare_fraction((an, ad): (u64, u64), (bn, bd): (u64, u64)) -> Ordering {
(an*bd).cmp(&(bn*ad))
(an * bd).cmp(&(bn * ad))
}

// Computes the nominator of the absolute difference between two such fractions.
fn abs_diff_nom((an, ad): (u64, u64), (bn, bd): (u64, u64)) -> u64 {
let c0 = an*bd;
let c1 = ad*bn;
let c0 = an * bd;
let c1 = ad * bn;

let d0 = c0.max(c1);
let d1 = c0.min(c1);
Expand All @@ -207,7 +209,7 @@ impl Delay {
// The upper bound fraction, numerator and denominator.
let mut upper = (1u64, 1u64);
// The closest approximation for now.
let mut guess = (u64::from(nom*2 > denom), 1u64);
let mut guess = (u64::from(nom * 2 > denom), 1u64);

// loop invariant: ad, bd <= denom_bound
// iterates the Farey sequence.
Expand Down Expand Up @@ -243,14 +245,19 @@ impl Delay {
// The difference |n - f| is smaller than |g - f| if either the integral part of the
// fraction |n_diff_nom|/nd is smaller than the one of |g_diff_nom|/gd or if they are
// the same but the fractional part is larger.
if match (n_diff_nom/next.1).cmp(&(g_diff_nom/guess.1)) {
if match (n_diff_nom / next.1).cmp(&(g_diff_nom / guess.1)) {
Less => true,
Greater => false,
// Note that the nominator for the fractional part is smaller than its denominator
// which is smaller than u32 and can't overflow the multiplication with the other
// denominator, that is we can compare these fractions by multiplication with the
// respective other denominator.
Equal => compare_fraction((n_diff_nom%next.1, next.1), (g_diff_nom%guess.1, guess.1)) == Less,
Equal => {
compare_fraction(
(n_diff_nom % next.1, next.1),
(g_diff_nom % guess.1, guess.1),
) == Less
}
} {
guess = next;
}
Expand Down Expand Up @@ -306,7 +313,8 @@ mod tests {
let delay = Delay::from_saturating_duration(inbounds);
assert_eq!(delay.numer_denom_ms(), (0xFFFF_FFFF, 1));

let fine = Duration::from_millis(0xFFFF_FFFF/1000) + Duration::from_micros(0xFFFF_FFFF%1000);
let fine =
Duration::from_millis(0xFFFF_FFFF / 1000) + Duration::from_micros(0xFFFF_FFFF % 1000);
let delay = Delay::from_saturating_duration(fine);
// Funnily, 0xFFFF_FFFF is divisble by 5, thus we compare with a `Ratio`.
assert_eq!(delay.into_ratio(), Ratio::new(0xFFFF_FFFF, 1000));
Expand All @@ -321,7 +329,6 @@ mod tests {
assert_eq!(Duration::from(delay), exceed);
}


#[test]
fn small() {
// Not quite a delay of `1 ms`.
Expand Down
Loading

0 comments on commit 183e74e

Please sign in to comment.