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

Clippy fixes with the new defaults #148

Merged
merged 1 commit into from
Jan 26, 2023
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
10 changes: 5 additions & 5 deletions limitador-server/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ fn generate_protobuf() -> Result<(), Box<dyn Error>> {

fn set_features(env: &str) {
if cfg!(feature = "infinispan") {
println!("cargo:rustc-env={}=[+infinispan]", env);
println!("cargo:rustc-env={env}=[+infinispan]");
}
}

fn set_profile(env: &str) {
if let Ok(profile) = std::env::var("PROFILE") {
println!("cargo:rustc-env={}={}", env, profile);
println!("cargo:rustc-env={env}={profile}");
}
}

Expand All @@ -50,14 +50,14 @@ fn set_git_hash(env: &str) {
.map(|output| !matches!(output.stdout.len(), 0));

match dirty {
Some(true) => println!("cargo:rustc-env={}={}-dirty", env, sha),
Some(false) => println!("cargo:rustc-env={}={}", env, sha),
Some(true) => println!("cargo:rustc-env={env}={sha}-dirty"),
Some(false) => println!("cargo:rustc-env={env}={sha}"),
_ => unreachable!("How can we have a git hash, yet not know if the tree is dirty?"),
}
} else {
let fallback = option_env!("GITHUB_SHA")
.map(|sha| if sha.len() > 8 { &sha[..8] } else { sha })
.unwrap_or("NO_SHA");
println!("cargo:rustc-env={}={}", env, fallback);
println!("cargo:rustc-env={env}={fallback}");
}
}
2 changes: 1 addition & 1 deletion limitador-server/src/http_api/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ mod tests {

// Read limit created
let req = test::TestRequest::get()
.uri(&format!("/limits/{}", namespace))
.uri(&format!("/limits/{namespace}"))
.data(data.clone())
.to_request();
let resp_limits: Vec<Limit> = test::call_and_read_body_json(&app, req).await;
Expand Down
36 changes: 16 additions & 20 deletions limitador-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl Limiter {
match AsyncRedisStorage::new(redis_url).await {
Ok(storage) => storage,
Err(err) => {
eprintln!("Failed to connect to Redis at {}: {}", redis_url, err);
eprintln!("Failed to connect to Redis at {redis_url}: {err}");
process::exit(1)
}
}
Expand Down Expand Up @@ -143,7 +143,7 @@ impl Limiter {
match cached_redis_storage.build().await {
Ok(storage) => storage,
Err(err) => {
eprintln!("Failed to connect to Redis at {}: {}", redis_url, err);
eprintln!("Failed to connect to Redis at {redis_url}: {err}");
process::exit(1)
}
}
Expand Down Expand Up @@ -229,13 +229,11 @@ impl Limiter {
Ok(())
}
Some(index) => Err(LimitadorServerError::ConfigFile(format!(
".[{}]: invalid value for `max_value`: positive integer expected",
index
".[{index}]: invalid value for `max_value`: positive integer expected"
))),
},
Err(e) => Err(LimitadorServerError::ConfigFile(format!(
"Couldn't parse: {}",
e
"Couldn't parse: {e}"
))),
}
}
Expand All @@ -261,7 +259,7 @@ fn find_first_negative_limit(limits: &[Limit]) -> Option<usize> {
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = {
let (config, version) = create_config();
println!("{} {}", LIMITADOR_HEADER, version);
println!("{LIMITADOR_HEADER} {version}");
let mut builder = Builder::new();
if let Some(level) = config.log_level {
builder.filter(None, level);
Expand All @@ -282,14 +280,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let rate_limiter: Arc<Limiter> = match Limiter::new(config).await {
Ok(limiter) => Arc::new(limiter),
Err(e) => {
eprintln!("Error: {}", e);
eprintln!("Error: {e}");
process::exit(1)
}
};

info!("limits file path: {}", limit_file);
if let Err(e) = rate_limiter.load_limits_from_file(&limit_file).await {
eprintln!("Failed to load limit file: {}", e);
eprintln!("Failed to load limit file: {e}");
process::exit(1)
}

Expand Down Expand Up @@ -373,7 +371,7 @@ fn create_config() -> (Configuration, String) {
let full_version = {
let build = match LIMITADOR_PROFILE {
"release" => "".to_owned(),
other => format!(" {} build", other),
other => format!(" {other} build"),
};

format!(
Expand Down Expand Up @@ -594,8 +592,7 @@ fn create_config() -> (Configuration, String) {
match parsed_limits {
Ok(limits) => match find_first_negative_limit(&limits) {
Some(index) => LimitadorServerError::ConfigFile(format!(
".[{}]: invalid value for `max_value`: positive integer expected",
index
".[{index}]: invalid value for `max_value`: positive integer expected"
)),
None => {
if limitador::limit::check_deprecated_syntax_usages_and_reset() {
Expand All @@ -606,24 +603,23 @@ fn create_config() -> (Configuration, String) {
limits.iter().map(|l| l.into()).collect();
match serde_yaml::to_string(&output) {
Ok(cfg) => {
println!("{}", cfg);
println!("{cfg}");
}
Err(err) => {
eprintln!("Config file is valid, but can't be output: {}", err);
eprintln!("Config file is valid, but can't be output: {err}");
}
}
process::exit(0);
}
},
Err(e) => LimitadorServerError::ConfigFile(format!("Couldn't parse: {}", e)),
Err(e) => LimitadorServerError::ConfigFile(format!("Couldn't parse: {e}")),
}
}
Err(e) => LimitadorServerError::ConfigFile(format!(
"Couldn't read file '{}': {}",
limits_file, e
)),
Err(e) => {
LimitadorServerError::ConfigFile(format!("Couldn't read file '{limits_file}': {e}"))
}
};
eprintln!("{}", error);
eprintln!("{error}");
process::exit(1);
}

Expand Down
18 changes: 9 additions & 9 deletions limitador/benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,23 +69,23 @@ fn bench_in_mem(c: &mut Criterion) {
BenchmarkId::new("is_rate_limited", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(InMemoryStorage::default());
let storage = Box::<limitador::storage::in_memory::InMemoryStorage>::default();
bench_is_rate_limited(b, test_scenario, storage);
},
);
group.bench_with_input(
BenchmarkId::new("update_counters", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(InMemoryStorage::default());
let storage = Box::<limitador::storage::in_memory::InMemoryStorage>::default();
bench_update_counters(b, test_scenario, storage);
},
);
group.bench_with_input(
BenchmarkId::new("check_rate_limited_and_update", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(InMemoryStorage::default());
let storage = Box::<limitador::storage::in_memory::InMemoryStorage>::default();
bench_check_rate_limited_and_update(b, test_scenario, storage);
},
);
Expand All @@ -101,23 +101,23 @@ fn bench_redis(c: &mut Criterion) {
BenchmarkId::new("is_rate_limited", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(RedisStorage::default());
let storage = Box::<limitador::storage::redis::RedisStorage>::default();
bench_is_rate_limited(b, test_scenario, storage);
},
);
group.bench_with_input(
BenchmarkId::new("update_counters", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(RedisStorage::default());
let storage = Box::<limitador::storage::redis::RedisStorage>::default();
bench_update_counters(b, test_scenario, storage);
},
);
group.bench_with_input(
BenchmarkId::new("check_rate_limited_and_update", scenario),
scenario,
|b: &mut Bencher, test_scenario: &&TestScenario| {
let storage = Box::new(RedisStorage::default());
let storage = Box::<limitador::storage::redis::RedisStorage>::default();
bench_check_rate_limited_and_update(b, test_scenario, storage);
},
);
Expand Down Expand Up @@ -210,14 +210,14 @@ fn generate_test_data(

let mut conditions = vec![];
for idx_cond in 0..scenario.n_conds_per_limit {
let cond_name = format!("cond_{}", idx_cond);
conditions.push(format!("{} == '1'", cond_name));
let cond_name = format!("cond_{idx_cond}");
conditions.push(format!("{cond_name} == '1'"));
test_values.insert(cond_name, "1".into());
}

let mut variables = vec![];
for idx_var in 0..scenario.n_vars_per_limit {
let var_name = format!("var_{}", idx_var);
let var_name = format!("var_{idx_var}");
variables.push(var_name.clone());
test_values.insert(var_name, "1".into());
}
Expand Down
25 changes: 9 additions & 16 deletions limitador/src/limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,7 @@ impl TryFrom<String> for Condition {
})
} else {
panic!(
"Unexpected state {:?} returned from Scanner for: `{}`",
tokens, value
"Unexpected state {tokens:?} returned from Scanner for: `{value}`"
)
}
}
Expand All @@ -163,8 +162,7 @@ impl TryFrom<String> for Condition {
})
} else {
panic!(
"Unexpected state {:?} returned from Scanner for: `{}`",
tokens, value
"Unexpected state {tokens:?} returned from Scanner for: `{value}`"
)
}
}
Expand All @@ -183,8 +181,7 @@ impl TryFrom<String> for Condition {
})
} else {
panic!(
"Unexpected state {:?} returned from Scanner for: `{}`",
tokens, value
"Unexpected state {tokens:?} returned from Scanner for: `{value}`"
)
}
}
Expand All @@ -203,8 +200,7 @@ impl TryFrom<String> for Condition {
})
} else {
panic!(
"Unexpected state {:?} returned from Scanner for: `{}`",
tokens, value
"Unexpected state {tokens:?} returned from Scanner for: `{value}`"
)
}
}
Expand Down Expand Up @@ -501,9 +497,9 @@ mod conditions {
impl Display for Literal {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Literal::Identifier(id) => write!(f, "{}", id),
Literal::String(string) => write!(f, "'{}'", string),
Literal::Number(number) => write!(f, "{}", number),
Literal::Identifier(id) => write!(f, "{id}"),
Literal::String(string) => write!(f, "'{string}'"),
Literal::Number(number) => write!(f, "{number}"),
}
}
}
Expand Down Expand Up @@ -819,9 +815,7 @@ mod conditions {

#[test]
fn unclosed_string_literal() {
let error = Scanner::scan("foo == 'ba".to_owned())
.err()
.expect("Should fail!");
let error = Scanner::scan("foo == 'ba".to_owned()).expect_err("Should fail!");
assert_eq!(error.pos, 8);
assert_eq!(error.error, ErrorType::UnclosedStringLiteral('\''));
}
Expand Down Expand Up @@ -993,8 +987,7 @@ mod tests {
#[test]
fn invalid_condition_parsing() {
let result = serde_json::from_str::<Condition>(r#""x != 5 && x > 12""#)
.err()
.expect("should fail parsing");
.expect_err("should fail parsing");
assert_eq!(
result.to_string(),
"SyntaxError: Invalid character `&` at offset 8 of condition \"x != 5 && x > 12\""
Expand Down