1
Fork 0

Use str::repeat

This commit is contained in:
Shotaro Yamada 2018-04-01 13:48:15 +09:00
parent 3d0e93309d
commit 3525368a56
10 changed files with 24 additions and 41 deletions

View file

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
use std::iter;
use core::num::dec2flt::parse::{Decimal, parse_decimal}; use core::num::dec2flt::parse::{Decimal, parse_decimal};
use core::num::dec2flt::parse::ParseResult::{Valid, Invalid}; use core::num::dec2flt::parse::ParseResult::{Valid, Invalid};
@ -46,7 +45,7 @@ fn valid() {
assert_eq!(parse_decimal("1.e300"), Valid(Decimal::new(b"1", b"", 300))); assert_eq!(parse_decimal("1.e300"), Valid(Decimal::new(b"1", b"", 300)));
assert_eq!(parse_decimal(".1e300"), Valid(Decimal::new(b"", b"1", 300))); assert_eq!(parse_decimal(".1e300"), Valid(Decimal::new(b"", b"1", 300)));
assert_eq!(parse_decimal("101e-33"), Valid(Decimal::new(b"101", b"", -33))); assert_eq!(parse_decimal("101e-33"), Valid(Decimal::new(b"101", b"", -33)));
let zeros: String = iter::repeat('0').take(25).collect(); let zeros = "0".repeat(25);
let s = format!("1.5e{}", zeros); let s = format!("1.5e{}", zeros);
assert_eq!(parse_decimal(&s), Valid(Decimal::new(b"1", b"5", 0))); assert_eq!(parse_decimal(&s), Valid(Decimal::new(b"1", b"5", 0)));
} }

View file

@ -17,7 +17,6 @@ use std::collections::HashMap;
use std::ffi::CString; use std::ffi::CString;
use std::fmt::Debug; use std::fmt::Debug;
use std::hash::{Hash, BuildHasher}; use std::hash::{Hash, BuildHasher};
use std::iter::repeat;
use std::panic; use std::panic;
use std::env; use std::env;
use std::path::Path; use std::path::Path;
@ -219,7 +218,7 @@ fn print_time_passes_entry_internal(what: &str, dur: Duration) {
None => "".to_owned(), None => "".to_owned(),
}; };
println!("{}time: {}{}\t{}", println!("{}time: {}{}\t{}",
repeat(" ").take(indentation).collect::<String>(), " ".repeat(indentation),
duration_to_secs_str(dur), duration_to_secs_str(dur),
mem_string, mem_string,
what); what);

View file

@ -98,7 +98,6 @@ use std::error::Error;
use std::ffi::OsString; use std::ffi::OsString;
use std::fmt::{self, Display}; use std::fmt::{self, Display};
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
use std::iter::repeat;
use std::mem; use std::mem;
use std::panic; use std::panic;
use std::path::{PathBuf, Path}; use std::path::{PathBuf, Path};
@ -1253,9 +1252,7 @@ Available lint options:
.max() .max()
.unwrap_or(0); .unwrap_or(0);
let padded = |x: &str| { let padded = |x: &str| {
let mut s = repeat(" ") let mut s = " ".repeat(max_name_len - x.chars().count());
.take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x); s.push_str(x);
s s
}; };
@ -1287,9 +1284,7 @@ Available lint options:
.unwrap_or(0)); .unwrap_or(0));
let padded = |x: &str| { let padded = |x: &str| {
let mut s = repeat(" ") let mut s = " ".repeat(max_name_len - x.chars().count());
.take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x); s.push_str(x);
s s
}; };

View file

@ -901,9 +901,7 @@ impl EmitterWriter {
// | | length of label // | | length of label
// | magic `3` // | magic `3`
// `max_line_num_len` // `max_line_num_len`
let padding = (0..padding + label.len() + 5) let padding = " ".repeat(padding + label.len() + 5);
.map(|_| " ")
.collect::<String>();
/// Return whether `style`, or the override if present and the style is `NoStyle`. /// Return whether `style`, or the override if present and the style is `NoStyle`.
fn style_or_override(style: Style, override_style: Option<Style>) -> Style { fn style_or_override(style: Style, override_style: Option<Style>) -> Style {

View file

@ -32,7 +32,7 @@ use arena::TypedArena;
use std::cmp::{self, Ordering}; use std::cmp::{self, Ordering};
use std::fmt; use std::fmt;
use std::iter::{FromIterator, IntoIterator, repeat}; use std::iter::{FromIterator, IntoIterator};
pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>) pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
-> &'a Pattern<'tcx> -> &'a Pattern<'tcx>
@ -115,7 +115,7 @@ impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
}).collect(); }).collect();
let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1; let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
let br = repeat('+').take(total_width).collect::<String>(); let br = "+".repeat(total_width);
write!(f, "{}\n", br)?; write!(f, "{}\n", br)?;
for row in pretty_printed_matrix { for row in pretty_printed_matrix {
write!(f, "+")?; write!(f, "+")?;

View file

@ -16,7 +16,6 @@
//! them in the future to instead emit any format desired. //! them in the future to instead emit any format desired.
use std::fmt; use std::fmt;
use std::iter::repeat;
use rustc::hir::def_id::DefId; use rustc::hir::def_id::DefId;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
@ -235,10 +234,9 @@ impl<'a> fmt::Display for WhereClause<'a> {
if !f.alternate() { if !f.alternate() {
clause.push_str("</span>"); clause.push_str("</span>");
let padding = repeat("&nbsp;").take(indent + 4).collect::<String>(); let padding = "&nbsp;".repeat(indent + 4);
clause = clause.replace("<br>", &format!("<br>{}", padding)); clause = clause.replace("<br>", &format!("<br>{}", padding));
clause.insert_str(0, &repeat("&nbsp;").take(indent.saturating_sub(1)) clause.insert_str(0, &"&nbsp;".repeat(indent.saturating_sub(1)));
.collect::<String>());
if !end_newline { if !end_newline {
clause.insert_str(0, "<br>"); clause.insert_str(0, "<br>");
} }
@ -409,13 +407,13 @@ pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone()); let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
let (fqp, shortty, mut url) = match cache.paths.get(&did) { let (fqp, shortty, mut url) = match cache.paths.get(&did) {
Some(&(ref fqp, shortty)) => { Some(&(ref fqp, shortty)) => {
(fqp, shortty, repeat("../").take(loc.len()).collect()) (fqp, shortty, "../".repeat(loc.len()))
} }
None => { None => {
let &(ref fqp, shortty) = cache.external_paths.get(&did)?; let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
(fqp, shortty, match cache.extern_locations[&did.krate] { (fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(), (.., render::Remote(ref s)) => s.to_string(),
(.., render::Local) => repeat("../").take(loc.len()).collect(), (.., render::Local) => "../".repeat(loc.len()),
(.., render::Unknown) => return None, (.., render::Unknown) => return None,
}) })
} }
@ -481,7 +479,7 @@ fn primitive_link(f: &mut fmt::Formatter,
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len()); let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
let len = if len == 0 {0} else {len - 1}; let len = if len == 0 {0} else {len - 1};
write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">", write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
repeat("../").take(len).collect::<String>(), "../".repeat(len),
prim.to_url_str())?; prim.to_url_str())?;
needs_termination = true; needs_termination = true;
} }
@ -492,7 +490,7 @@ fn primitive_link(f: &mut fmt::Formatter,
} }
(ref cname, _, render::Local) => { (ref cname, _, render::Local) => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len()); let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
Some((cname, repeat("../").take(len).collect::<String>())) Some((cname, "../".repeat(len)))
} }
(.., render::Unknown) => None, (.., render::Unknown) => None,
}; };
@ -903,15 +901,15 @@ impl<'a> fmt::Display for Method<'a> {
format!("{}", decl.output) format!("{}", decl.output)
}; };
let pad = repeat(" ").take(name_len).collect::<String>(); let pad = " ".repeat(name_len);
let plain = format!("{pad}({args}){arrow}", let plain = format!("{pad}({args}){arrow}",
pad = pad, pad = pad,
args = args_plain, args = args_plain,
arrow = arrow_plain); arrow = arrow_plain);
let output = if plain.len() > 80 { let output = if plain.len() > 80 {
let full_pad = format!("<br>{}", repeat("&nbsp;").take(indent + 4).collect::<String>()); let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
let close_pad = format!("<br>{}", repeat("&nbsp;").take(indent).collect::<String>()); let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
format!("({args}{close}){arrow}", format!("({args}{close}){arrow}",
args = args.replace("<br>", &full_pad), args = args.replace("<br>", &full_pad),
close = close_pad, close = close_pad,

View file

@ -46,7 +46,6 @@ use std::ffi::OsStr;
use std::fs::{self, File, OpenOptions}; use std::fs::{self, File, OpenOptions};
use std::io::prelude::*; use std::io::prelude::*;
use std::io::{self, BufWriter, BufReader}; use std::io::{self, BufWriter, BufReader};
use std::iter::repeat;
use std::mem; use std::mem;
use std::path::{PathBuf, Path, Component}; use std::path::{PathBuf, Path, Component};
use std::str; use std::str;
@ -1712,7 +1711,7 @@ impl Context {
/// String representation of how to get back to the root path of the 'doc/' /// String representation of how to get back to the root path of the 'doc/'
/// folder in terms of a relative URL. /// folder in terms of a relative URL.
fn root_path(&self) -> String { fn root_path(&self) -> String {
repeat("../").take(self.current.len()).collect::<String>() "../".repeat(self.current.len())
} }
/// Recurse in the directory structure and change the "root path" to make /// Recurse in the directory structure and change the "root path" to make
@ -2113,8 +2112,7 @@ impl<'a> fmt::Display for Item<'a> {
let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() }; let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) { for (i, component) in cur.iter().enumerate().take(amt) {
write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>", write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
repeat("../").take(cur.len() - i - 1) "../".repeat(cur.len() - i - 1),
.collect::<String>(),
component)?; component)?;
} }
} }

View file

@ -11,7 +11,6 @@
extern crate rand; extern crate rand;
use std::env::*; use std::env::*;
use std::iter::repeat;
use std::ffi::{OsString, OsStr}; use std::ffi::{OsString, OsStr};
use rand::Rng; use rand::Rng;
@ -72,7 +71,7 @@ fn test_var_big() {
#[cfg_attr(target_os = "emscripten", ignore)] #[cfg_attr(target_os = "emscripten", ignore)]
fn test_env_set_get_huge() { fn test_env_set_get_huge() {
let n = make_rand_name(); let n = make_rand_name();
let s = repeat("x").take(10000).collect::<String>(); let s = "x".repeat(10000);
set_var(&n, &s); set_var(&n, &s);
eq(var_os(&n), Some(&s)); eq(var_os(&n), Some(&s));
remove_var(&n); remove_var(&n);

View file

@ -32,7 +32,7 @@ use tokenstream::{self, TokenStream, TokenTree};
use std::ascii; use std::ascii;
use std::io::{self, Write, Read}; use std::io::{self, Write, Read};
use std::iter::{self, Peekable}; use std::iter::Peekable;
use std::vec; use std::vec;
pub enum AnnNode<'a> { pub enum AnnNode<'a> {
@ -235,11 +235,11 @@ pub fn token_to_string(tok: &Token) -> String {
token::Integer(c) => c.to_string(), token::Integer(c) => c.to_string(),
token::Str_(s) => format!("\"{}\"", s), token::Str_(s) => format!("\"{}\"", s),
token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}", token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
delim=repeat("#", n as usize), delim="#".repeat(n as usize),
string=s), string=s),
token::ByteStr(v) => format!("b\"{}\"", v), token::ByteStr(v) => format!("b\"{}\"", v),
token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}", token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
delim=repeat("#", n as usize), delim="#".repeat(n as usize),
string=s), string=s),
}; };
@ -661,7 +661,7 @@ pub trait PrintState<'a> {
} }
ast::StrStyle::Raw(n) => { ast::StrStyle::Raw(n) => {
(format!("r{delim}\"{string}\"{delim}", (format!("r{delim}\"{string}\"{delim}",
delim=repeat("#", n as usize), delim="#".repeat(n as usize),
string=st)) string=st))
} }
}; };
@ -3180,8 +3180,6 @@ impl<'a> State<'a> {
} }
} }
fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View file

@ -66,7 +66,6 @@ use std::fmt;
use std::fs::File; use std::fs::File;
use std::io::prelude::*; use std::io::prelude::*;
use std::io; use std::io;
use std::iter::repeat;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Termination; use std::process::Termination;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
@ -145,7 +144,7 @@ impl TestDesc {
fn padded_name(&self, column_count: usize, align: NamePadding) -> String { fn padded_name(&self, column_count: usize, align: NamePadding) -> String {
let mut name = String::from(self.name.as_slice()); let mut name = String::from(self.name.as_slice());
let fill = column_count.saturating_sub(name.len()); let fill = column_count.saturating_sub(name.len());
let pad = repeat(" ").take(fill).collect::<String>(); let pad = " ".repeat(fill);
match align { match align {
PadNone => name, PadNone => name,
PadOnRight => { PadOnRight => {