Skip to content

Update string formatting for Rust 1.88 compatibility #494

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 3 additions & 5 deletions benches/bench_redirect_performance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn get_redirect_rules() -> Vec<NetworkFilter> {
.map(|(index, mut rule)| {
rule.mask.insert(NetworkFilterMask::IS_LEFT_ANCHOR);
rule.mask.insert(NetworkFilterMask::IS_RIGHT_ANCHOR);
rule.hostname = Some(format!("a{}.com/bad.js", index));
rule.hostname = Some(format!("a{index}.com/bad.js"));

rule.filter = adblock::filters::network::FilterPart::Empty;
rule.mask.remove(NetworkFilterMask::IS_HOSTNAME_ANCHOR);
Expand Down Expand Up @@ -204,7 +204,7 @@ pub fn build_custom_requests(rules: Vec<NetworkFilter>) -> Vec<Request> {
hostname
};

let source_url = format!("https://{}", source_hostname);
let source_url = format!("https://{source_hostname}");

Request::new(&url, &source_url, raw_type).unwrap()
})
Expand All @@ -216,9 +216,7 @@ fn bench_fn(blocker: &Blocker, resources: &ResourceStorage, requests: &[Request]
let block_result = blocker.check(request, resources);
assert!(
block_result.redirect.is_some(),
"{:?}, {:?}",
request,
block_result
"{request:?}, {block_result:?}"
);
});
}
Expand Down
6 changes: 3 additions & 3 deletions examples/deserialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn load_requests() -> Vec<RequestRuleMatch> {
if let Ok(record) = result {
reqs.push(record);
} else {
println!("Could not parse {:?}", result);
println!("Could not parse {result:?}");
}
}

Expand Down Expand Up @@ -70,7 +70,7 @@ fn main() {
let mut false_negative_exceptions: HashMap<String, (String, String, String)> = HashMap::new();
for (reqs_processed, req) in requests.into_iter().enumerate() {
if reqs_processed % 10000 == 0 {
println!("{} requests processed", reqs_processed);
println!("{reqs_processed} requests processed");
}
let request = Request::new(&req.url, &req.sourceUrl, &req.r#type).unwrap();
let checked = engine.check_network_request(&request);
Expand Down Expand Up @@ -106,7 +106,7 @@ fn main() {

let mismatches = mismatch_expected_match + mismatch_expected_exception + mismatch_expected_pass;
let ratio = mismatches as f32 / requests_len as f32;
assert!(ratio < 0.04, "Mismatch ratio was {}", ratio);
assert!(ratio < 0.04, "Mismatch ratio was {ratio}");
assert!(
false_positive_rules.len() < 3,
"False positive rules higher than expected: {:?}",
Expand Down
2 changes: 1 addition & 1 deletion examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ fn main() {
.unwrap();
let blocker_result = engine.check_network_request(&request);

println!("Blocker result: {:?}", blocker_result);
println!("Blocker result: {blocker_result:?}");
}
2 changes: 1 addition & 1 deletion examples/use-dat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ fn main() {
let checked = engine.check_network_request(&request);
assert!(checked.filter.is_some());
assert!(checked.exception.is_some());
println!("All good: {:?}", checked);
println!("All good: {checked:?}");
}
2 changes: 1 addition & 1 deletion fuzz/fuzz_targets/parse_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
if let Ok(url) = std::str::from_utf8(data) {
Request::new(&format!("https://{}", url), "https://example.com", "other");
Request::new(&format!("https://{url}"), "https://example.com", "other");
Request::new(url, "https://example.com", "script");
Request::new(url, "", "");
Request::new(url, url, "");
Expand Down
10 changes: 5 additions & 5 deletions js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ fn filter_set_into_content_blocking(mut cx: FunctionContext) -> JsResult<JsValue
};
json_ffi::to_js(&mut cx, &r)
}
Err(_) => return Ok(JsUndefined::new(&mut cx).upcast()),
Err(_) => Ok(JsUndefined::new(&mut cx).upcast()),
}
}

Expand Down Expand Up @@ -266,7 +266,7 @@ fn engine_deserialize(mut cx: FunctionContext) -> JsResult<JsNull> {
let serialized_handle = cx.argument::<JsArrayBuffer>(1)?;

if let Ok(mut engine) = this.0.lock() {
let _result = engine.deserialize(&serialized_handle.as_slice(&mut cx));
let _result = engine.deserialize(serialized_handle.as_slice(&cx));
}

Ok(JsNull::new(&mut cx))
Expand Down Expand Up @@ -360,13 +360,13 @@ fn ublock_resources(mut cx: FunctionContext) -> JsResult<JsValue> {
};

let mut resources = assemble_web_accessible_resources(
&Path::new(&web_accessible_resource_dir),
&Path::new(&redirect_resources_path),
Path::new(&web_accessible_resource_dir),
Path::new(&redirect_resources_path),
);
if let Some(scriptlets_path) = scriptlets_path {
#[allow(deprecated)]
resources.append(
&mut adblock::resources::resource_assembler::assemble_scriptlet_resources(&Path::new(
&mut adblock::resources::resource_assembler::assemble_scriptlet_resources(Path::new(
&scriptlets_path,
)),
);
Expand Down
6 changes: 3 additions & 3 deletions src/blocker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ impl Blocker {
impl std::fmt::Display for QParam<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::KeyOnly(k) => write!(f, "{}", k),
Self::KeyValue(k, v) => write!(f, "{}={}", k, v),
Self::KeyOnly(k) => write!(f, "{k}"),
Self::KeyValue(k, v) => write!(f, "{k}={v}"),
}
}
}
Expand Down Expand Up @@ -317,7 +317,7 @@ impl Blocker {
let new_param_str = if p.is_empty() {
String::from("")
} else {
format!("?{}", p)
format!("?{p}")
};
Some(format!(
"{}{}{}",
Expand Down
8 changes: 4 additions & 4 deletions src/content_blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ impl TryFrom<NetworkFilter> for CbRuleEquivalent {
let with_fixed_wildcards =
REPLACE_WILDCARDS.replace_all(&escaped_special_chars, ".*");
let mut url_filter = if v.mask.contains(NetworkFilterMask::IS_LEFT_ANCHOR) {
format!("^{}", with_fixed_wildcards)
format!("^{with_fixed_wildcards}")
} else {
let scheme_part = if v
.mask
Expand All @@ -394,7 +394,7 @@ impl TryFrom<NetworkFilter> for CbRuleEquivalent {
unreachable!("Invalid scheme information");
};

format!("{}{}", scheme_part, with_fixed_wildcards)
format!("{scheme_part}{with_fixed_wildcards}")
};

if v.mask.contains(NetworkFilterMask::IS_RIGHT_ANCHOR) {
Expand All @@ -405,7 +405,7 @@ impl TryFrom<NetworkFilter> for CbRuleEquivalent {
}
(crate::filters::network::FilterPart::Empty, Some(hostname)) => {
let escaped_special_chars = SPECIAL_CHARS.replace_all(&hostname, r##"\$1"##);
format!("^[^:]+:(//)?([^/]+\\.)?{}", escaped_special_chars)
format!("^[^:]+:(//)?([^/]+\\.)?{escaped_special_chars}")
}
(crate::filters::network::FilterPart::Empty, None) => if v
.mask
Expand Down Expand Up @@ -464,7 +464,7 @@ impl TryFrom<NetworkFilter> for CbRuleEquivalent {
idna::domain_to_ascii(&lowercase).unwrap()
};

collection.push(format!("*{}", normalized_domain));
collection.push(format!("*{normalized_domain}"));
});

(non_empty(if_domain), non_empty(unless_domain))
Expand Down
9 changes: 4 additions & 5 deletions src/cosmetic_filter_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,9 @@ impl CosmeticFilterCache {

classes.into_iter().for_each(|class| {
let class = class.as_ref();
if self.simple_class_rules.contains(class)
&& !exceptions.contains(&format!(".{}", class))
if self.simple_class_rules.contains(class) && !exceptions.contains(&format!(".{class}"))
{
selectors.push(format!(".{}", class));
selectors.push(format!(".{class}"));
}
if let Some(bucket) = self.complex_class_rules.get(class) {
selectors.extend(
Expand All @@ -209,8 +208,8 @@ impl CosmeticFilterCache {
});
ids.into_iter().for_each(|id| {
let id = id.as_ref();
if self.simple_id_rules.contains(id) && !exceptions.contains(&format!("#{}", id)) {
selectors.push(format!("#{}", id));
if self.simple_id_rules.contains(id) && !exceptions.contains(&format!("#{id}")) {
selectors.push(format!("#{id}"));
}
if let Some(bucket) = self.complex_id_rules.get(id) {
selectors.extend(
Expand Down
28 changes: 14 additions & 14 deletions src/filters/cosmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,7 @@ mod css_validation {

// Use `mock-stylesheet-marker` where uBO uses `color: red` since we have control over the
// parsing logic within the block.
let mock_stylesheet = format!("{}{{mock-stylesheet-marker}}", selector);
let mock_stylesheet = format!("{selector}{{mock-stylesheet-marker}}");
let mut pi = ParserInput::new(&mock_stylesheet);
let mut parser = Parser::new(&mut pi);
let mut rule_list_parser = cssparser::RuleListParser::new_for_stylesheet(
Expand Down Expand Up @@ -1104,17 +1104,17 @@ mod css_validation {
fn to_css<W: Write>(&self, dest: &mut W) -> FmtResult {
write!(dest, ":")?;
match self {
Self::HasText(text) => write!(dest, "has-text({})", text)?,
Self::MatchesAttr(text) => write!(dest, "matches-attr({})", text)?,
Self::MatchesCss(text) => write!(dest, "matches-css({})", text)?,
Self::MatchesCssBefore(text) => write!(dest, "matches-css-before({})", text)?,
Self::MatchesCssAfter(text) => write!(dest, "matches-css-after({})", text)?,
Self::MatchesPath(text) => write!(dest, "matches-path({})", text)?,
Self::MinTextLength(text) => write!(dest, "min-text-length({})", text)?,
Self::Upward(text) => write!(dest, "upward({})", text)?,
Self::Xpath(text) => write!(dest, "xpath({})", text)?,
Self::AnythingElse(name, None) => write!(dest, "{}", name)?,
Self::AnythingElse(name, Some(args)) => write!(dest, "{}({})", name, args)?,
Self::HasText(text) => write!(dest, "has-text({text})")?,
Self::MatchesAttr(text) => write!(dest, "matches-attr({text})")?,
Self::MatchesCss(text) => write!(dest, "matches-css({text})")?,
Self::MatchesCssBefore(text) => write!(dest, "matches-css-before({text})")?,
Self::MatchesCssAfter(text) => write!(dest, "matches-css-after({text})")?,
Self::MatchesPath(text) => write!(dest, "matches-path({text})")?,
Self::MinTextLength(text) => write!(dest, "min-text-length({text})")?,
Self::Upward(text) => write!(dest, "upward({text})")?,
Self::Xpath(text) => write!(dest, "xpath({text})")?,
Self::AnythingElse(name, None) => write!(dest, "{name}")?,
Self::AnythingElse(name, Some(args)) => write!(dest, "{name}({args})")?,
}
Ok(())
}
Expand Down Expand Up @@ -1165,8 +1165,8 @@ mod css_validation {
fn to_css<W: Write>(&self, dest: &mut W) -> FmtResult {
write!(dest, "::")?;
match self {
Self(name, None) => write!(dest, "{}", name)?,
Self(name, Some(args)) => write!(dest, "{}({})", name, args)?,
Self(name, None) => write!(dest, "{name}")?,
Self(name, Some(args)) => write!(dest, "{name}({args})")?,
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/network_filter_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl From<&NetworkFilter> for CheckResult {
impl fmt::Display for CheckResult {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if let Some(ref raw_line) = self.raw_line {
write!(f, "{}", raw_line)
write!(f, "{raw_line}")
} else {
write!(f, "{}", self.filter_mask)
}
Expand Down
2 changes: 1 addition & 1 deletion src/regex_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ where
// Should match start or end of url
let left_anchor = if is_left_anchor { "^" } else { "" };
let right_anchor = if is_right_anchor { "$" } else { "" };
let filter = format!("{}{}{}", left_anchor, repl, right_anchor);
let filter = format!("{left_anchor}{repl}{right_anchor}");

escaped_patterns.push(filter);
}
Expand Down
4 changes: 2 additions & 2 deletions src/resources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ impl MimeType {
"xml" => MimeType::TextXml,
_ => {
#[cfg(test)]
eprintln!("Unrecognized file extension on: {:?}", resource_path);
eprintln!("Unrecognized file extension on: {resource_path:?}");
MimeType::Unknown
}
}
Expand Down Expand Up @@ -332,7 +332,7 @@ impl From<MimeType> for &str {
impl std::fmt::Display for MimeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s: &str = self.into();
write!(f, "{}", s)
write!(f, "{s}")
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/resources/resource_assembler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ fn read_resource_from_web_accessible_dir(
) -> Resource {
let resource_path = web_accessible_resource_dir.join(&resource_info.name);
if !resource_path.is_file() {
panic!("Expected {:?} to be a file", resource_path);
panic!("Expected {resource_path:?} to be a file");
}
let mut resource_file = File::open(resource_path).expect("open resource file for reading");
let mut resource_contents = Vec::new();
Expand Down
8 changes: 4 additions & 4 deletions src/resources/resource_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ fn stringify_arg<const QUOTED: bool>(arg: &str) -> String {
start = index + 1;
}
if escape == b'u' {
output.extend_from_slice(format!("{:04x}", ch).as_bytes());
output.extend_from_slice(format!("{ch:04x}").as_bytes());
}
}
output.extend_from_slice(&string.as_bytes()[start..]);
Expand Down Expand Up @@ -121,7 +121,7 @@ impl ResourceStorage {
#[allow(clippy::unnecessary_lazy_evaluations)]
self_.add_resource(resource).unwrap_or_else(|_e| {
#[cfg(test)]
eprintln!("Failed to add resource: {:?}", _e)
eprintln!("Failed to add resource: {_e:?}")
})
});

Expand Down Expand Up @@ -388,7 +388,7 @@ static TEMPLATE_ARGUMENT_RE: [Lazy<Regex>; 9] = [
];

fn template_argument_regex(i: usize) -> Regex {
Regex::new(&format!(r"\{{\{{{}\}}\}}", i)).unwrap()
Regex::new(&format!(r"\{{\{{{i}\}}\}}")).unwrap()
}

/// Omit the 0th element of `args` (the scriptlet name) when calling this method.
Expand All @@ -415,7 +415,7 @@ fn with_js_extension(scriptlet_name: &str) -> String {
if scriptlet_name.ends_with(".js") {
scriptlet_name.to_string()
} else {
format!("{}.js", scriptlet_name)
format!("{scriptlet_name}.js")
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/url_parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,10 +529,10 @@ impl Parser {
}

if host_str.is_ascii() {
write!(&mut self.serialization, "{}", host_str).unwrap();
write!(&mut self.serialization, "{host_str}").unwrap();
} else {
let encoded = idna::domain_to_ascii(host_str)?;
write!(&mut self.serialization, "{}", encoded).unwrap();
write!(&mut self.serialization, "{encoded}").unwrap();
}

let host_end = self.serialization.len();
Expand Down
10 changes: 2 additions & 8 deletions tests/legacy_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ mod legacy_test_filters {

assert_eq!(
filter.mask, expected_filter_mask,
"Filter {} mask doesn't match expectation",
raw_filter
"Filter {raw_filter} mask doesn't match expectation"
);

let filter_string = filter.filter.string_view();
Expand Down Expand Up @@ -511,12 +510,7 @@ mod legacy_check_options {
let request = Request::new(url, source_url, request_type).unwrap();
assert!(
engine.check_network_request(&request).matched == *expectation,
"Expected match = {} for {} from {} typed {} against {:?}",
expectation,
url,
source_url,
request_type,
rules
"Expected match = {expectation} for {url} from {source_url} typed {request_type} against {rules:?}"
)
}
}
Expand Down
Loading