Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Code Quality in a few places #803

Merged
merged 1 commit into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ include = [
]
edition = "2021"
resolver = "2"
rust-version = "1.70"
rust-version = "1.71"

[package.metadata.docs.rs]
all-features = true
Expand Down Expand Up @@ -59,7 +59,6 @@ sha2 = { version = "0.10.8", default-features = false }
slab = { version = "0.4.9", default-features = false }
smallstr = { version = "0.3.0", default-features = false }
snafu = { version = "0.8.0", default-features = false }
unicase = "2.6.0"

# std
image = { version = "0.25.0", features = [
Expand Down
1 change: 1 addition & 0 deletions crates/livesplit-auto-splitting/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ license = "MIT OR Apache-2.0"
description = "livesplit-auto-splitting is a library that provides a runtime for running auto splitters that can control a speedrun timer. These auto splitters are provided as WebAssembly modules."
keywords = ["speedrun", "timer", "livesplit", "auto-splitting"]
edition = "2021"
rust-version = "1.74"

[dependencies]
anyhow = { version = "1.0.45", default-features = false }
Expand Down
1 change: 1 addition & 0 deletions crates/livesplit-auto-splitting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@
missing_docs,
rust_2018_idioms
)]
#![forbid(clippy::incompatible_msrv)]

mod process;
mod runtime;
Expand Down
1 change: 1 addition & 0 deletions crates/livesplit-hotkey/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ license = "MIT OR Apache-2.0"
description = "livesplit-hotkey provides cross-platform global hotkey hooks."
keywords = ["speedrun", "timer", "livesplit", "hotkey", "keyboard"]
edition = "2021"
rust-version = "1.73"

[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.52.0", features = [
Expand Down
1 change: 1 addition & 0 deletions crates/livesplit-hotkey/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
missing_docs,
rust_2018_idioms
)]
#![forbid(clippy::incompatible_msrv)]
#![cfg_attr(not(feature = "std"), no_std)]

//! `livesplit-hotkey` is a crate that allows listening to hotkeys even when the
Expand Down
4 changes: 1 addition & 3 deletions crates/livesplit-title-abbreviations/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,4 @@ license = "MIT OR Apache-2.0"
description = "livesplit-title-abbreviations encapsulates the algorithm that LiveSplit uses to abbreviate game titles."
keywords = ["speedrun", "timer", "livesplit", "title", "abbreviation"]
edition = "2018"

[dependencies]
unicase = "2.6.0"
rust-version = "1.70"
1 change: 1 addition & 0 deletions crates/livesplit-title-abbreviations/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// missing_docs,
rust_2018_idioms
)]
#![forbid(clippy::incompatible_msrv)]
#![no_std]

extern crate alloc;
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
missing_docs,
rust_2018_idioms
)]
#![forbid(clippy::incompatible_msrv)]
// Clippy false positives
#![allow(
clippy::blocks_in_conditions,
Expand Down
1 change: 1 addition & 0 deletions src/platform/no_std/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub fn register_clock(clock: impl Clock) {
}

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(Duration);

impl Instant {
Expand Down
34 changes: 33 additions & 1 deletion src/platform/normal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ cfg_if::cfg_if! {
use core::{mem::MaybeUninit, ops::Sub};

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(Duration);

impl Instant {
Expand Down Expand Up @@ -156,6 +157,7 @@ cfg_if::cfg_if! {
}

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(u64);

impl Instant {
Expand Down Expand Up @@ -187,7 +189,37 @@ cfg_if::cfg_if! {
}
}
} else {
pub use time::Instant;
use core::ops::Sub;

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(std::time::Instant);

impl Instant {
/// Accesses the current point in time.
#[inline]
pub fn now() -> Self {
Self(std::time::Instant::now())
}
}

impl Sub<Duration> for Instant {
type Output = Instant;

#[inline]
fn sub(self, rhs: Duration) -> Instant {
Self(time::ext::InstantExt::sub_signed(self.0, rhs))
}
}

impl Sub for Instant {
type Output = Duration;

#[inline]
fn sub(self, rhs: Instant) -> Duration {
time::ext::InstantExt::signed_duration_since(&self.0, rhs.0)
}
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/platform/wasm/unknown/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ extern "C" {
}

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(Duration);

impl Instant {
Expand Down
1 change: 1 addition & 0 deletions src/platform/wasm/web/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use web_sys::Performance;
pub use time::{Duration, OffsetDateTime as DateTime};

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Debug)]
#[repr(transparent)]
pub struct Instant(Duration);

thread_local! {
Expand Down
16 changes: 14 additions & 2 deletions src/rendering/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
//! then be attached anywhere in the DOM with any desired positioning and size.

use bytemuck::cast;
use hashbrown::HashMap;
use js_sys::{Array, JsString, Uint8Array};
use std::{
array,
cell::{Cell, RefCell},
collections::HashMap,
f64::consts::TAU,
ops::Deref,
rc::Rc,
Expand Down Expand Up @@ -597,7 +597,19 @@ impl Renderer {
match background {
Background::Shader(shader) => {
set_fill_style(shader, ctx, &mut self.cache, str_buf, &*scene.rectangle());
ctx.fill_rect(0.0, 0.0, width, height);
// Instead of scaling the rectangle we need to use a
// transform so that the gradient's endpoints are
// correct.
set_transform(
ctx,
&Transform {
x: 0.0,
y: 0.0,
scale_x: width as _,
scale_y: height as _,
},
);
ctx.fill_rect(0.0, 0.0, 1.0, 1.0);
}
Background::Image(background_image, transform) => {
let image = background_image.image.0.borrow();
Expand Down
10 changes: 7 additions & 3 deletions src/run/editor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@

use super::{ComparisonError, ComparisonResult, LinkedLayout};
use crate::{
comparison, platform::prelude::*, settings::Image, timing::ParseError as ParseTimeSpanError,
util::PopulateString, Run, Segment, Time, TimeSpan, TimingMethod,
comparison,
platform::prelude::*,
settings::Image,
timing::ParseError as ParseTimeSpanError,
util::{caseless, PopulateString},
Run, Segment, Time, TimeSpan, TimingMethod,
};
use core::{mem::swap, num::ParseIntError};
use snafu::{OptionExt, ResultExt};
Expand Down Expand Up @@ -758,7 +762,7 @@
if let Some((segment_index, my_segment)) = remaining_segments
.iter_mut()
.enumerate()
.find(|(_, s)| unicase::eq(segment.name(), s.name()))
.find(|(_, s)| caseless::eq(segment.name(), s.name()))
{
*my_segment.comparison_mut(comparison) = segment.personal_best_split_time();
remaining_segments = &mut remaining_segments[segment_index + 1..];
Expand Down Expand Up @@ -835,7 +839,7 @@
/// `src_index` specified to the `dst_index` specified. Returns `Err(())` if
/// one of the indices is invalid. The indices are based on the
/// `comparison_names` field of the Run Editor's `State`.
pub fn move_comparison(&mut self, src_index: usize, dst_index: usize) -> Result<(), ()> {

Check warning on line 842 in src/run/editor/mod.rs

View workflow job for this annotation

GitHub Actions / Check clippy lints

this returns a `Result<_, ()>`
let comparisons = self.run.custom_comparisons_mut();
let (src_index, dst_index) = (src_index + 1, dst_index + 1);
if src_index >= comparisons.len() || dst_index >= comparisons.len() {
Expand Down
6 changes: 3 additions & 3 deletions src/run/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use crate::{
comparison::{default_generators, personal_best, ComparisonGenerator, RACE_COMPARISON_PREFIX},
platform::prelude::*,
settings::Image,
util::PopulateString,
util::{caseless::matches_ascii_key, PopulateString},
AtomicDateTime, Time, TimeSpan, TimingMethod,
};
use alloc::borrow::Cow;
Expand Down Expand Up @@ -907,9 +907,9 @@ impl fmt::Display for ExtendedCategoryName<'_> {
for (name, value) in self.run.metadata.speedrun_com_variables() {
let name = name.trim_end_matches('?');

if unicase::eq(value.as_str(), "yes") {
if matches_ascii_key("yes", value) {
push(&[name])?;
} else if unicase::eq(value.as_str(), "no") {
} else if matches_ascii_key("no", value) {
push(&["No ", value])?;
} else {
push(&[value])?;
Expand Down
1 change: 1 addition & 0 deletions src/timing/time_span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use snafu::{ensure, OptionExt, ResultExt};

/// A `TimeSpan` represents a certain span of time.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct TimeSpan(Duration);

impl TimeSpan {
Expand Down
4 changes: 4 additions & 0 deletions src/timing/time_stamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ use core::ops::Sub;
/// A `TimeStamp` stores a point in time that can be used to calculate a
/// [`TimeSpan`].
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[repr(transparent)]
pub struct TimeStamp(Instant);

impl TimeStamp {
/// Creates a new `TimeStamp`, representing the current point in time.
#[inline]
pub fn now() -> Self {
TimeStamp(Instant::now())
}
Expand All @@ -19,6 +21,7 @@ impl TimeStamp {
impl Sub for TimeStamp {
type Output = TimeSpan;

#[inline]
fn sub(self, rhs: TimeStamp) -> TimeSpan {
TimeSpan::from(self.0 - rhs.0)
}
Expand All @@ -27,6 +30,7 @@ impl Sub for TimeStamp {
impl Sub<TimeSpan> for TimeStamp {
type Output = TimeStamp;

#[inline]
fn sub(self, rhs: TimeSpan) -> TimeStamp {
TimeStamp(self.0 - Duration::from(rhs))
}
Expand Down
6 changes: 3 additions & 3 deletions src/util/byte_parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub mod big_endian {
u16::from_be_bytes(self.0)
}

#[cfg(any(windows, feature = "default-text-engine"))]
#[cfg(any(all(windows, feature = "std"), feature = "default-text-engine"))]
pub const fn usize(self) -> usize {
self.get() as usize
}
Expand Down Expand Up @@ -85,12 +85,12 @@ pub fn strip_slice<'a, T: AnyBitPattern>(cursor: &mut &'a [u8], n: usize) -> Opt
Some(bytemuck::cast_slice(before))
}

#[cfg(any(windows, feature = "default-text-engine"))]
#[cfg(any(all(windows, feature = "std"), feature = "default-text-engine"))]
pub fn pod<P: AnyBitPattern>(bytes: &[u8]) -> Option<&P> {
Some(bytemuck::from_bytes(bytes.get(..mem::size_of::<P>())?))
}

#[cfg(any(windows, feature = "default-text-engine"))]
#[cfg(any(all(windows, feature = "std"), feature = "default-text-engine"))]
pub fn slice<P: AnyBitPattern>(bytes: &[u8], n: usize) -> Option<&[P]> {
Some(bytemuck::cast_slice(bytes.get(..n * mem::size_of::<P>())?))
}
14 changes: 14 additions & 0 deletions src/util/caseless.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
pub fn eq(a: &str, b: &str) -> bool {
Iterator::eq(
a.chars().flat_map(|c| c.to_lowercase()),
b.chars().flat_map(|c| c.to_lowercase()),
)
}

/// The key needs to already be lowercase.
pub fn matches_ascii_key(key: &str, input: &str) -> bool {
key.len() == input.len()
&& key
.bytes()
.eq(input.bytes().map(|b| b.to_ascii_lowercase()))
}
1 change: 1 addition & 0 deletions src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
pub(crate) mod ascii_char;
pub(crate) mod ascii_set;
pub(crate) mod byte_parsing;
pub(crate) mod caseless;
mod clear_vec;
#[cfg(any(feature = "image-shrinking", feature = "svg-rendering"))]
pub(crate) mod image;
Expand Down
3 changes: 2 additions & 1 deletion src/util/populate_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ impl PopulateString for String {
impl PopulateString for &str {
// If the string doesn't fit into the capacity of the buffer, we just
// allocate a new buffer instead of forcing it to reallocate, which would
// mean copying all the bytes of the previous buffer, which we don't care about.
// mean copying all the bytes of the previous buffer, which we don't care
// about.
#[allow(clippy::assigning_clones)]
fn populate(self, buf: &mut String) {
if self.len() <= buf.capacity() {
Expand Down
Loading