Auto merge of #52767 - ljedrz:avoid_format, r=petrochenkov

Prefer to_string() to format!()

Simple benchmarks suggest in some cases it can be faster by even 37%:
```
test converting_f64_long  ... bench:         339 ns/iter (+/- 199)
test converting_f64_short ... bench:         136 ns/iter (+/- 34)
test converting_i32_long  ... bench:          87 ns/iter (+/- 16)
test converting_i32_short ... bench:          87 ns/iter (+/- 49)
test converting_str       ... bench:          54 ns/iter (+/- 15)
test formatting_f64_long  ... bench:         349 ns/iter (+/- 176)
test formatting_f64_short ... bench:         145 ns/iter (+/- 14)
test formatting_i32_long  ... bench:          98 ns/iter (+/- 14)
test formatting_i32_short ... bench:          93 ns/iter (+/- 15)
test formatting_str       ... bench:          86 ns/iter (+/- 23)
```
This commit is contained in:
bors 2018-07-29 09:33:37 +00:00
commit 023fd7e74a
36 changed files with 95 additions and 95 deletions

View File

@ -925,7 +925,7 @@ impl<'a> Builder<'a> {
cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
}
cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
// in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) {

View File

@ -79,7 +79,7 @@ fn chunks() {
fn display() {
assert_eq!(
"Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye",
&format!("{}", Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye")));
&Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").to_string());
}
#[test]

View File

@ -557,7 +557,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
// Output the lifetimes fot the first type
let lifetimes = sub.regions()
.map(|lifetime| {
let s = format!("{}", lifetime);
let s = lifetime.to_string();
if s.is_empty() {
"'_".to_string()
} else {
@ -582,7 +582,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
value.0.extend((values.0).0);
other_value.0.extend((values.1).0);
} else {
value.push_highlighted(format!("{}", type_arg));
value.push_highlighted(type_arg.to_string());
}
if len > 0 && i != len - 1 {
@ -716,7 +716,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
mutbl: hir::Mutability,
s: &mut DiagnosticStyledString,
) {
let r = &format!("{}", r);
let r = &r.to_string();
s.push_highlighted(format!(
"&{}{}{}",
r,
@ -727,7 +727,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
""
}
));
s.push_normal(format!("{}", ty));
s.push_normal(ty.to_string());
}
match (&t1.sty, &t2.sty) {
@ -768,7 +768,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
}
fn lifetime_display(lifetime: Region) -> String {
let s = format!("{}", lifetime);
let s = lifetime.to_string();
if s.is_empty() {
"'_".to_string()
} else {
@ -863,8 +863,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
// We couldn't find anything in common, highlight everything.
// let x: Bar<Qux> = y::<Foo<Zar>>();
(
DiagnosticStyledString::highlighted(format!("{}", t1)),
DiagnosticStyledString::highlighted(format!("{}", t2)),
DiagnosticStyledString::highlighted(t1.to_string()),
DiagnosticStyledString::highlighted(t2.to_string()),
)
}
}
@ -873,12 +873,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
(&ty::TyRef(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
values.1.push_normal(format!("{}", t2));
values.1.push_normal(t2.to_string());
values
}
(_, &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
values.0.push_normal(format!("{}", t1));
values.0.push_normal(t1.to_string());
push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
values
}
@ -902,8 +902,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
} else {
// We couldn't find anything in common, highlight everything.
(
DiagnosticStyledString::highlighted(format!("{}", t1)),
DiagnosticStyledString::highlighted(format!("{}", t2)),
DiagnosticStyledString::highlighted(t1.to_string()),
DiagnosticStyledString::highlighted(t2.to_string()),
)
}
}
@ -1073,8 +1073,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
}
Some((
DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
DiagnosticStyledString::highlighted(format!("{}", exp_found.found)),
DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
DiagnosticStyledString::highlighted(exp_found.found.to_string()),
))
}

View File

@ -57,7 +57,7 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> {
let lifetime_name = match sup_r {
RegionKind::ReFree(FreeRegion {
bound_region: BoundRegion::BrNamed(_, ref name), ..
}) => format!("{}", name),
}) => name.to_string(),
_ => "'_".to_owned(),
};
if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(return_sp) {

View File

@ -2093,7 +2093,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
// When printing regions, add trailing space if necessary.
let region = if ppaux::verbose() || ppaux::identify_regions() {
let mut region = format!("{}", region);
let mut region = region.to_string();
if region.len() > 0 {
region.push(' ');
}

View File

@ -135,8 +135,8 @@ impl CodeStats {
let VariantInfo { ref name, kind: _, align: _, size, ref fields } = *variant_info;
let indent = if !struct_like {
let name = match name.as_ref() {
Some(name) => format!("{}", name),
None => format!("{}", i),
Some(name) => name.to_owned(),
None => i.to_string(),
};
println!("print-type-size {}variant `{}`: {} bytes",
indent, name, size - discr_size);

View File

@ -543,7 +543,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
&data.parent_trait_ref);
match self.get_parent_trait_ref(&data.parent_code) {
Some(t) => Some(t),
None => Some(format!("{}", parent_trait_ref.skip_binder().self_ty())),
None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
}
}
_ => None,
@ -797,12 +797,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
ty::TypeVariants::TyTuple(ref tys) => ArgKind::Tuple(
Some(span),
tys.iter()
.map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
.map(|ty| ("_".to_owned(), ty.sty.to_string()))
.collect::<Vec<_>>()
),
_ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
_ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),
}).collect(),
ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
ref sty => vec![ArgKind::Arg("_".to_owned(), sty.to_string())],
};
if found.len() == expected.len() {
self.report_closure_arg_mismatch(span,
@ -989,7 +989,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
}) => {
(self.tcx.sess.codemap().def_span(span),
fields.iter().map(|field| {
ArgKind::Arg(format!("{}", field.ident), "_".to_string())
ArgKind::Arg(field.ident.to_string(), "_".to_string())
}).collect::<Vec<_>>())
}
hir::map::NodeStructCtor(ref variant_data) => {
@ -1152,7 +1152,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
::rustc_target::spec::abi::Abi::Rust
)
};
format!("{}", ty::Binder::bind(sig))
ty::Binder::bind(sig).to_string()
}
let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
@ -1575,10 +1575,10 @@ impl ArgKind {
ty::TyTuple(ref tys) => ArgKind::Tuple(
None,
tys.iter()
.map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
.map(|ty| ("_".to_owned(), ty.sty.to_string()))
.collect::<Vec<_>>()
),
_ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
_ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),
}
}
}

View File

@ -315,7 +315,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
ty::TyUint(_) |
ty::TyFloat(_) |
ty::TyStr => {
buffer.push(&format!("{}", self_ty));
buffer.push(&self_ty.to_string());
}
_ => {

View File

@ -225,7 +225,7 @@ impl AssociatedItem {
// late-bound regions, and we don't want method signatures to show up
// `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
// regions just fine, showing `fn(&MyType)`.
format!("{}", tcx.fn_sig(self.def_id).skip_binder())
tcx.fn_sig(self.def_id).skip_binder().to_string()
}
ty::AssociatedKind::Type => format!("type {};", self.ident),
ty::AssociatedKind::Existential => format!("existential type {};", self.ident),

View File

@ -242,7 +242,7 @@ pub fn to_readable_str(mut val: usize) -> String {
val /= 1000;
if val == 0 {
groups.push(format!("{}", group));
groups.push(group.to_string());
break;
} else {
groups.push(format!("{:03}", group));

View File

@ -697,7 +697,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
let mut err = self.cannot_act_on_moved_value(use_span,
verb,
msg,
Some(format!("{}", nl)),
Some(nl.to_string()),
Origin::Ast);
let need_note = match lp.ty.sty {
ty::TypeVariants::TyClosure(id, _) => {

View File

@ -149,7 +149,7 @@ impl<'a> ArchiveBuilder<'a> {
// Ignoring obj file starting with the crate name
// as simple comparison is not enough - there
// might be also an extra name suffix
let obj_start = format!("{}", name);
let obj_start = name.to_owned();
self.add_archive(rlib, move |fname: &str| {
// Ignore bytecode/metadata files, no matter the name.

View File

@ -811,7 +811,7 @@ fn link_natively(sess: &Session,
}
};
linker_error.note(&format!("{}", e));
linker_error.note(&e.to_string());
if !linker_not_found {
linker_error.note(&format!("{:?}", &cmd));

View File

@ -530,7 +530,7 @@ fn run_compiler_with_pool<'a>(
if let Some(err) = input_err {
// Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8).
sess.err(&format!("{}", err));
sess.err(&err.to_string());
return (Err(CompileIncomplete::Stopped), Some(sess));
}
@ -1110,7 +1110,7 @@ impl RustcDefaultCalls {
cfgs.push(if let Some(value) = value {
format!("{}=\"{}\"", name, value)
} else {
format!("{}", name)
name.to_string()
});
}

View File

@ -190,7 +190,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
fieldpat.span,
&format!("the `{}:` in this pattern is redundant", ident));
let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
err.span_suggestion_short(subspan, "remove this", format!("{}", ident));
err.span_suggestion_short(subspan, "remove this", ident.to_string());
err.emit();
}
}
@ -701,7 +701,7 @@ impl EarlyLintPass for BadRepr {
attr.span,
"`repr` attribute isn't configurable with a literal",
);
match format!("{}", lit).as_ref() {
match lit.to_string().as_ref() {
| "C" | "packed" | "rust" | "transparent"
| "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {

View File

@ -722,7 +722,7 @@ impl<'a> Context<'a> {
root.triple);
self.rejected_via_triple.push(CrateMismatch {
path: libpath.to_path_buf(),
got: format!("{}", root.triple),
got: root.triple.to_string(),
});
return None;
}

View File

@ -86,7 +86,7 @@ impl<'tcx> fmt::Display for BorrowData<'tcx> {
mir::BorrowKind::Unique => "uniq ",
mir::BorrowKind::Mut { .. } => "mut ",
};
let region = format!("{}", self.region);
let region = self.region.to_string();
let region = if region.len() > 0 {
format!("{} ", region)
} else {

View File

@ -642,7 +642,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
self.append_local_to_string(local, buf)?;
}
Place::Static(ref static_) => {
buf.push_str(&format!("{}", &self.tcx.item_name(static_.def_id)));
buf.push_str(&self.tcx.item_name(static_.def_id).to_string());
}
Place::Projection(ref proj) => {
match proj.elem {
@ -766,7 +766,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
let local = &self.mir.local_decls[local_index];
match local.name {
Some(name) => {
buf.push_str(&format!("{}", name));
buf.push_str(&name.to_string());
Ok(())
}
None => Err(()),
@ -794,7 +794,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
ProjectionElem::Index(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. } => {
format!("{}", self.describe_field(&proj.base, field))
self.describe_field(&proj.base, field).to_string()
}
},
}
@ -808,11 +808,11 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
} else {
match ty.sty {
ty::TyAdt(def, _) => if def.is_enum() {
format!("{}", field.index())
field.index().to_string()
} else {
format!("{}", def.non_enum_variant().fields[field.index()].ident)
def.non_enum_variant().fields[field.index()].ident.to_string()
},
ty::TyTuple(_) => format!("{}", field.index()),
ty::TyTuple(_) => field.index().to_string(),
ty::TyRef(_, ty, _) | ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => {
self.describe_field_from_ty(&ty, field)
}

View File

@ -114,7 +114,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> {
};
saw_one = true;
let borrow_data = &self.borrows.operator().borrows()[borrow];
s.push_str(&format!("{}", borrow_data));
s.push_str(&borrow_data.to_string());
});
s.push_str("] ");
@ -126,7 +126,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> {
};
saw_one = true;
let borrow_data = &self.borrows.operator().borrows()[borrow];
s.push_str(&format!("{}", borrow_data));
s.push_str(&borrow_data.to_string());
});
s.push_str("] ");
@ -138,7 +138,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> {
};
saw_one = true;
let move_path = &self.uninits.operator().move_data().move_paths[mpi_uninit];
s.push_str(&format!("{}", move_path));
s.push_str(&move_path.to_string());
});
s.push_str("] ");

View File

@ -307,7 +307,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
err.span_suggestion(
span,
"consider removing this dereference operator",
format!("{}", &snippet[1..]),
(&snippet[1..]).to_owned(),
);
}
_ => {

View File

@ -523,7 +523,7 @@ impl<'a, 'tcx> ClauseDumper<'a, 'tcx> {
Clause::Implies(program_clause) => program_clause,
Clause::ForAll(program_clause) => program_clause.skip_binder(),
};
format!("{}", program_clause)
program_clause.to_string()
})
.collect();

View File

@ -2838,7 +2838,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
ty::TyFnDef(..) => {
let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx));
let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
variadic_error(tcx.sess, arg.span, arg_ty, &format!("{}", ptr_ty));
variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string());
}
_ => {}
}

View File

@ -54,9 +54,9 @@ fn inferred_outlives_of<'a, 'tcx>(
let mut pred: Vec<String> = predicates
.iter()
.map(|out_pred| match out_pred {
ty::Predicate::RegionOutlives(p) => format!("{}", &p),
ty::Predicate::RegionOutlives(p) => p.to_string(),
ty::Predicate::TypeOutlives(p) => format!("{}", &p),
ty::Predicate::TypeOutlives(p) => p.to_string(),
err => bug!("unexpected predicate {:?}", err),
})

View File

@ -206,7 +206,7 @@ impl<'a> fmt::Display for WhereClause<'a> {
clause.push_str(" + ");
}
clause.push_str(&format!("{}", lifetime));
clause.push_str(&lifetime.to_string());
}
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
@ -458,10 +458,10 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
fqp[..fqp.len() - 1].join("::"),
HRef::new(did, fqp.last().unwrap()))
}
None => format!("{}", HRef::new(did, &last.name)),
None => HRef::new(did, &last.name).to_string(),
}
} else {
format!("{}", HRef::new(did, &last.name))
HRef::new(did, &last.name).to_string()
};
write!(w, "{}{}", path, last.args)?;
}
@ -883,7 +883,7 @@ impl<'a> fmt::Display for Method<'a> {
if f.alternate() {
args.push_str(&format!("{:#}", input.type_));
} else {
args.push_str(&format!("{}", input.type_));
args.push_str(&input.type_.to_string());
}
args_plain.push_str(&format!("{:#}", input.type_));
}
@ -902,7 +902,7 @@ impl<'a> fmt::Display for Method<'a> {
let arrow = if f.alternate() {
format!("{:#}", decl.output)
} else {
format!("{}", decl.output)
decl.output.to_string()
};
let pad = " ".repeat(name_len);

View File

@ -881,14 +881,14 @@ mod tests {
#[test]
fn issue_17736() {
let markdown = "# title";
format!("{}", Markdown(markdown, &[]));
Markdown(markdown, &[]).to_string();
reset_ids(true);
}
#[test]
fn test_header() {
fn t(input: &str, expect: &str) {
let output = format!("{}", Markdown(input, &[]));
let output = Markdown(input, &[]).to_string();
assert_eq!(output, expect, "original: {}", input);
reset_ids(true);
}
@ -910,7 +910,7 @@ mod tests {
#[test]
fn test_header_ids_multiple_blocks() {
fn t(input: &str, expect: &str) {
let output = format!("{}", Markdown(input, &[]));
let output = Markdown(input, &[]).to_string();
assert_eq!(output, expect, "original: {}", input);
}
@ -951,7 +951,7 @@ mod tests {
#[test]
fn test_markdown_html_escape() {
fn t(input: &str, expect: &str) {
let output = format!("{}", MarkdownHtml(input));
let output = MarkdownHtml(input).to_string();
assert_eq!(output, expect, "original: {}", input);
}

View File

@ -2058,7 +2058,7 @@ impl<'a> Item<'a> {
};
let lines = if self.item.source.loline == self.item.source.hiline {
format!("{}", self.item.source.loline)
self.item.source.loline.to_string()
} else {
format!("{}-{}", self.item.source.loline, self.item.source.hiline)
};
@ -2233,7 +2233,7 @@ fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLin
format!("{} [Read more]({})",
&plain_summary_line(Some(s)), naive_assoc_href(item, link))
} else {
format!("{}", &plain_summary_line(Some(s)))
plain_summary_line(Some(s)).to_string()
};
render_markdown(w, &markdown, item.links(), prefix)?;
} else if !prefix.is_empty() {
@ -2730,7 +2730,7 @@ fn bounds(t_bounds: &[clean::GenericBound]) -> String {
bounds.push_str(" + ");
bounds_plain.push_str(" + ");
}
bounds.push_str(&format!("{}", *p));
bounds.push_str(&(*p).to_string());
bounds_plain.push_str(&format!("{:#}", *p));
}
}
@ -3391,7 +3391,7 @@ fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
let name = attr.name();
if attr.is_word() {
Some(format!("{}", name))
Some(name.to_string())
} else if let Some(v) = attr.value_str() {
Some(format!("{} = {:?}", name, v.as_str()))
} else if let Some(values) = attr.meta_item_list() {
@ -3639,7 +3639,7 @@ fn render_assoc_items(w: &mut fmt::Formatter,
}
}
let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
let impls = RendererStruct(cx, concrete, containing_item).to_string();
if !impls.is_empty() {
write!(w, "\
<h2 id='implementations' class='small-section-header'>\
@ -3755,7 +3755,7 @@ fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
&format!("<h3 class=\"important\">Important traits for {}</h3>\
<code class=\"content\">",
impl_.for_));
trait_.push_str(&format!("{}", impl_.for_));
trait_.push_str(&impl_.for_.to_string());
}
//use the "where" class here to make it small

View File

@ -157,7 +157,7 @@ impl TocBuilder {
sec_number.push_str("0.");
}
let number = toc.count_entries_with_level(level);
sec_number.push_str(&format!("{}", number + 1))
sec_number.push_str(&(number + 1).to_string())
}
self.chain.push(TocEntry {

View File

@ -89,9 +89,9 @@ pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches,
reset_ids(false);
let text = if include_toc {
format!("{}", MarkdownWithToc(text))
MarkdownWithToc(text).to_string()
} else {
format!("{}", Markdown(text, &[]))
Markdown(text, &[]).to_string()
};
let err = write!(

View File

@ -2094,7 +2094,7 @@ macro_rules! expect {
match $e {
Json::Null => Ok(()),
other => Err(ExpectedError("Null".to_owned(),
format!("{}", other)))
other.to_string()))
}
});
($e:expr, $t:ident) => ({
@ -2102,7 +2102,7 @@ macro_rules! expect {
Json::$t(v) => Ok(v),
other => {
Err(ExpectedError(stringify!($t).to_owned(),
format!("{}", other)))
other.to_string()))
}
}
})
@ -2114,14 +2114,14 @@ macro_rules! read_primitive {
match self.pop() {
Json::I64(f) => Ok(f as $ty),
Json::U64(f) => Ok(f as $ty),
Json::F64(f) => Err(ExpectedError("Integer".to_owned(), format!("{}", f))),
Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
// re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
// is going to have a string here, as per JSON spec.
Json::String(s) => match s.parse().ok() {
Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_owned(), s)),
},
value => Err(ExpectedError("Number".to_owned(), format!("{}", value))),
value => Err(ExpectedError("Number".to_owned(), value.to_string())),
}
}
}
@ -2163,7 +2163,7 @@ impl ::Decoder for Decoder {
}
},
Json::Null => Ok(f64::NAN),
value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
value => Err(ExpectedError("Number".to_owned(), value.to_string()))
}
}
@ -2181,7 +2181,7 @@ impl ::Decoder for Decoder {
_ => ()
}
}
Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
Err(ExpectedError("single character string".to_owned(), s.to_string()))
}
fn read_str(&mut self) -> DecodeResult<Cow<str>> {
@ -2204,7 +2204,7 @@ impl ::Decoder for Decoder {
let n = match o.remove(&"variant".to_owned()) {
Some(Json::String(s)) => s,
Some(val) => {
return Err(ExpectedError("String".to_owned(), format!("{}", val)))
return Err(ExpectedError("String".to_owned(), val.to_string()))
}
None => {
return Err(MissingFieldError("variant".to_owned()))
@ -2217,7 +2217,7 @@ impl ::Decoder for Decoder {
}
},
Some(val) => {
return Err(ExpectedError("Array".to_owned(), format!("{}", val)))
return Err(ExpectedError("Array".to_owned(), val.to_string()))
}
None => {
return Err(MissingFieldError("fields".to_owned()))
@ -2226,7 +2226,7 @@ impl ::Decoder for Decoder {
n
}
json => {
return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
return Err(ExpectedError("String or Object".to_owned(), json.to_string()))
}
};
let idx = match names.iter().position(|n| *n == &name[..]) {
@ -2845,21 +2845,21 @@ mod tests {
fn test_write_enum() {
let animal = Dog;
assert_eq!(
format!("{}", super::as_json(&animal)),
super::as_json(&animal).to_string(),
"\"Dog\""
);
assert_eq!(
format!("{}", super::as_pretty_json(&animal)),
super::as_pretty_json(&animal).to_string(),
"\"Dog\""
);
let animal = Frog("Henry".to_string(), 349);
assert_eq!(
format!("{}", super::as_json(&animal)),
super::as_json(&animal).to_string(),
"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
);
assert_eq!(
format!("{}", super::as_pretty_json(&animal)),
super::as_pretty_json(&animal).to_string(),
"{\n \
\"variant\": \"Frog\",\n \
\"fields\": [\n \
@ -2872,10 +2872,10 @@ mod tests {
macro_rules! check_encoder_for_simple {
($value:expr, $expected:expr) => ({
let s = format!("{}", super::as_json(&$value));
let s = super::as_json(&$value).to_string();
assert_eq!(s, $expected);
let s = format!("{}", super::as_pretty_json(&$value));
let s = super::as_pretty_json(&$value).to_string();
assert_eq!(s, $expected);
})
}

View File

@ -58,7 +58,7 @@ impl UdpSocket {
pub fn recv(&self, buf: &mut [u8]) -> Result<usize> {
if let Some(addr) = *self.get_conn() {
let from = self.0.dup(format!("{}", addr).as_bytes())?;
let from = self.0.dup(addr.to_string().as_bytes())?;
from.read(buf)
} else {
Err(Error::new(ErrorKind::Other, "UdpSocket::recv not connected"))

View File

@ -1245,7 +1245,7 @@ mod tests {
#[test]
fn wtf8_display() {
fn d(b: &[u8]) -> String {
format!("{}", &unsafe { Wtf8::from_bytes_unchecked(b) })
(&unsafe { Wtf8::from_bytes_unchecked(b) }).to_string()
}
assert_eq!("", d("".as_bytes()));

View File

@ -380,7 +380,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
structs, enums and unions");
if let ast::AttrStyle::Inner = attr.style {
let trait_list = traits.iter()
.map(|t| format!("{}", t)).collect::<Vec<_>>();
.map(|t| t.to_string()).collect::<Vec<_>>();
let suggestion = format!("#[derive({})]", trait_list.join(", "));
err.span_suggestion_with_applicability(
span, "try an outer attribute", suggestion,
@ -558,7 +558,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
invoc.expansion_data.mark.set_expn_info(ExpnInfo {
call_site: attr.span,
def_site: None,
format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))),
format: MacroAttribute(Symbol::intern(&attr.path.to_string())),
allow_internal_unstable: false,
allow_internal_unsafe: false,
local_inner_macros: false,

View File

@ -6320,7 +6320,7 @@ impl<'a> Parser<'a> {
mod_name: mod_name.clone(),
default_path: default_path_str,
secondary_path: secondary_path_str,
dir_path: format!("{}", dir_path.display()),
dir_path: dir_path.display().to_string(),
}),
(true, true) => Err(Error::DuplicatePaths {
mod_name: mod_name.clone(),

View File

@ -631,7 +631,7 @@ pub trait PrintState<'a> {
self.writer().word(&ut.val_to_string(i))
}
ast::LitIntType::Unsuffixed => {
self.writer().word(&format!("{}", i))
self.writer().word(&i.to_string())
}
}
}

View File

@ -42,10 +42,10 @@ pub fn expand_syntax_ext(
ast::LitKind::Int(i, ast::LitIntType::Unsigned(_))
| ast::LitKind::Int(i, ast::LitIntType::Signed(_))
| ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
accumulator.push_str(&format!("{}", i));
accumulator.push_str(&i.to_string());
}
ast::LitKind::Bool(b) => {
accumulator.push_str(&format!("{}", b));
accumulator.push_str(&b.to_string());
}
ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..) => {
cx.span_err(e.span, "cannot concatenate a byte string literal");

View File

@ -189,7 +189,7 @@ pub fn parse(file: &mut dyn io::Read, longnames: bool) -> Result<TermInfo, Strin
macro_rules! t( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
Err(e) => return Err(e.to_string())
}
) );