A few cleanups for fmt_macros, graphviz, apfloat, target, serialize and term

This commit is contained in:
ljedrz 2018-08-10 13:13:50 +02:00
parent f6d43ed842
commit 535bd13fe4
10 changed files with 141 additions and 153 deletions

View File

@ -411,7 +411,7 @@ impl<'a> Parser<'a> {
// fill character
if let Some(&(_, c)) = self.cur.peek() {
match self.cur.clone().skip(1).next() {
match self.cur.clone().nth(1) {
Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
spec.fill = Some(c);
self.cur.next();
@ -504,13 +504,11 @@ impl<'a> Parser<'a> {
if word.is_empty() {
self.cur = tmp;
CountImplied
} else if self.consume('$') {
CountIsName(word)
} else {
if self.consume('$') {
CountIsName(word)
} else {
self.cur = tmp;
CountImplied
}
self.cur = tmp;
CountImplied
}
}
}

View File

@ -420,7 +420,8 @@ impl<'a> Id<'a> {
if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' ) {
return Err(());
}
return Ok(Id { name: name });
Ok(Id { name })
}
pub fn as_slice(&'a self) -> &'a str {
@ -533,10 +534,10 @@ impl<'a> LabelText<'a> {
/// Renders text as string suitable for a label in a .dot file.
/// This includes quotes or suitable delimiters.
pub fn to_dot_string(&self) -> String {
match self {
&LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
&EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)),
&HtmlStr(ref s) => format!("<{}>", s),
match *self {
LabelStr(ref s) => format!("\"{}\"", s.escape_default()),
EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)),
HtmlStr(ref s) => format!("<{}>", s),
}
}

View File

@ -536,23 +536,21 @@ impl<S: Semantics> fmt::Display for IeeeFloat<S> {
// Check whether we should use scientific notation.
let scientific = if width == 0 {
true
} else if exp >= 0 {
// 765e3 --> 765000
// ^^^
// But we shouldn't make the number look more precise than it is.
exp as usize > width || digits + exp as usize > precision
} else {
if exp >= 0 {
// 765e3 --> 765000
// ^^^
// But we shouldn't make the number look more precise than it is.
exp as usize > width || digits + exp as usize > precision
// Power of the most significant digit.
let msd = exp + (digits - 1) as ExpInt;
if msd >= 0 {
// 765e-2 == 7.65
false
} else {
// Power of the most significant digit.
let msd = exp + (digits - 1) as ExpInt;
if msd >= 0 {
// 765e-2 == 7.65
false
} else {
// 765e-5 == 0.00765
// ^ ^^
-msd as usize > width
}
// 765e-5 == 0.00765
// ^ ^^
-msd as usize > width
}
};
@ -702,7 +700,7 @@ impl<S: Semantics> Float for IeeeFloat<S> {
// exponent = 1..10
// significand = 1..1
IeeeFloat {
sig: [!0 & ((1 << S::PRECISION) - 1)],
sig: [(1 << S::PRECISION) - 1],
exp: S::MAX_EXP,
category: Category::Normal,
sign: false,
@ -1507,10 +1505,11 @@ impl<S: Semantics, T: Semantics> FloatConvert<IeeeFloat<T>> for IeeeFloat<S> {
}
// If this is a truncation, perform the shift.
let mut loss = Loss::ExactlyZero;
if shift < 0 && (r.is_finite_non_zero() || r.category == Category::NaN) {
loss = sig::shift_right(&mut r.sig, &mut 0, -shift as usize);
}
let loss = if shift < 0 && (r.is_finite_non_zero() || r.category == Category::NaN) {
sig::shift_right(&mut r.sig, &mut 0, -shift as usize)
} else {
Loss::ExactlyZero
};
// If this is an extension, perform the shift.
if shift > 0 && (r.is_finite_non_zero() || r.category == Category::NaN) {
@ -1738,27 +1737,25 @@ impl<S: Semantics> IeeeFloat<S> {
bit_pos -= 4;
if bit_pos >= 0 {
r.sig[0] |= (hex_value as Limb) << bit_pos;
} else {
// If zero or one-half (the hexadecimal digit 8) are followed
// by non-zero, they're a little more than zero or one-half.
if let Some(ref mut loss) = loss {
if hex_value != 0 {
if *loss == Loss::ExactlyZero {
*loss = Loss::LessThanHalf;
}
if *loss == Loss::ExactlyHalf {
*loss = Loss::MoreThanHalf;
}
// If zero or one-half (the hexadecimal digit 8) are followed
// by non-zero, they're a little more than zero or one-half.
} else if let Some(ref mut loss) = loss {
if hex_value != 0 {
if *loss == Loss::ExactlyZero {
*loss = Loss::LessThanHalf;
}
if *loss == Loss::ExactlyHalf {
*loss = Loss::MoreThanHalf;
}
} else {
loss = Some(match hex_value {
0 => Loss::ExactlyZero,
1..=7 => Loss::LessThanHalf,
8 => Loss::ExactlyHalf,
9..=15 => Loss::MoreThanHalf,
_ => unreachable!(),
});
}
} else {
loss = Some(match hex_value {
0 => Loss::ExactlyZero,
1..=7 => Loss::LessThanHalf,
8 => Loss::ExactlyHalf,
9..=15 => Loss::MoreThanHalf,
_ => unreachable!(),
});
}
} else if c == 'p' || c == 'P' {
if !any_digits {
@ -2309,9 +2306,9 @@ mod sig {
/// One, not zero, based LSB. That is, returns 0 for a zeroed significand.
pub(super) fn olsb(limbs: &[Limb]) -> usize {
for i in 0..limbs.len() {
if limbs[i] != 0 {
return i * LIMB_BITS + limbs[i].trailing_zeros() as usize + 1;
for (i, &limb) in limbs.iter().enumerate() {
if limb != 0 {
return i * LIMB_BITS + limb.trailing_zeros() as usize + 1;
}
}
@ -2320,9 +2317,9 @@ mod sig {
/// One, not zero, based MSB. That is, returns 0 for a zeroed significand.
pub(super) fn omsb(limbs: &[Limb]) -> usize {
for i in (0..limbs.len()).rev() {
if limbs[i] != 0 {
return (i + 1) * LIMB_BITS - limbs[i].leading_zeros() as usize;
for (i, &limb) in limbs.iter().enumerate().rev() {
if limb != 0 {
return (i + 1) * LIMB_BITS - limb.leading_zeros() as usize;
}
}
@ -2378,7 +2375,7 @@ mod sig {
limb = dst[i - jump];
if shift > 0 {
limb <<= shift;
if i >= jump + 1 {
if i > jump {
limb |= dst[i - jump - 1] >> (LIMB_BITS - shift);
}
}
@ -2448,7 +2445,7 @@ mod sig {
let n = dst_limbs * LIMB_BITS - shift;
if n < src_bits {
let mask = (1 << (src_bits - n)) - 1;
dst[dst_limbs - 1] |= (src[dst_limbs] & mask) << n % LIMB_BITS;
dst[dst_limbs - 1] |= (src[dst_limbs] & mask) << (n % LIMB_BITS);
} else if n > src_bits && src_bits % LIMB_BITS > 0 {
dst[dst_limbs - 1] &= (1 << (src_bits % LIMB_BITS)) - 1;
}

View File

@ -764,14 +764,10 @@ impl Target {
// the JSON parser is not updated to match the structs.
let get_req_field = |name: &str| {
match obj.find(name)
.map(|s| s.as_string())
.and_then(|os| os.map(|s| s.to_string())) {
Some(val) => Ok(val),
None => {
return Err(format!("Field {} in target specification is required", name))
}
}
obj.find(name)
.map(|s| s.as_string())
.and_then(|os| os.map(|s| s.to_string()))
.ok_or_else(|| format!("Field {} in target specification is required", name))
};
let get_opt_field = |name: &str, default: &str| {

View File

@ -22,7 +22,7 @@ pub trait ToHex {
fn to_hex(&self) -> String;
}
const CHARS: &'static [u8] = b"0123456789abcdef";
const CHARS: &[u8] = b"0123456789abcdef";
impl ToHex for [u8] {
/// Turn a vector of `u8` bytes into a hexadecimal string.

View File

@ -438,7 +438,7 @@ fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
}
fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
const BUF: &'static str = " ";
const BUF: &str = " ";
while n >= BUF.len() {
wr.write_str(BUF)?;
@ -799,21 +799,21 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
write!(self.writer, "{{\n")?;
writeln!(self.writer, "{{")?;
self.curr_indent += self.indent;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "\"variant\": ")?;
escape_str(self.writer, name)?;
write!(self.writer, ",\n")?;
writeln!(self.writer, ",")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "\"fields\": [\n")?;
writeln!(self.writer, "\"fields\": [")?;
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
write!(self.writer, "\n")?;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
self.curr_indent -= self.indent;
write!(self.writer, "]\n")?;
writeln!(self.writer, "]")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
Ok(())
@ -825,7 +825,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx != 0 {
write!(self.writer, ",\n")?;
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
f(self)
@ -864,7 +864,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
write!(self.writer, "\n")?;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
@ -876,9 +876,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
write!(self.writer, "\n")?;
writeln!(self.writer)?;
} else {
write!(self.writer, ",\n")?;
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
escape_str(self.writer, name)?;
@ -940,7 +940,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
write!(self.writer, "\n")?;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "]")?;
}
@ -952,9 +952,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
write!(self.writer, "\n")?;
writeln!(self.writer)?;
} else {
write!(self.writer, ",\n")?;
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
f(self)
@ -971,7 +971,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
write!(self.writer, "\n")?;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
@ -983,9 +983,9 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if idx == 0 {
write!(self.writer, "\n")?;
writeln!(self.writer)?;
} else {
write!(self.writer, ",\n")?;
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
self.is_emitting_map_key = true;
@ -1387,10 +1387,10 @@ impl Stack {
// Used by Parser to test whether the top-most element is an index.
fn last_is_index(&self) -> bool {
if self.is_empty() { return false; }
return match *self.stack.last().unwrap() {
InternalIndex(_) => true,
_ => false,
if let Some(InternalIndex(_)) = self.stack.last() {
true
} else {
false
}
}
@ -1530,19 +1530,17 @@ impl<T: Iterator<Item=char>> Parser<T> {
}
F64Value(res)
} else {
if neg {
let res = (res as i64).wrapping_neg();
} else if neg {
let res = (res as i64).wrapping_neg();
// Make sure we didn't underflow.
if res > 0 {
Error(SyntaxError(InvalidNumber, self.line, self.col))
} else {
I64Value(res)
}
// Make sure we didn't underflow.
if res > 0 {
Error(SyntaxError(InvalidNumber, self.line, self.col))
} else {
U64Value(res)
I64Value(res)
}
} else {
U64Value(res)
}
}

View File

@ -103,8 +103,8 @@ pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W)
loop {
let mut byte = (value as u8) & 0x7f;
value >>= 7;
let more = !((((value == 0) && ((byte & 0x40) == 0)) ||
((value == -1) && ((byte & 0x40) != 0))));
let more = !(((value == 0) && ((byte & 0x40) == 0)) ||
((value == -1) && ((byte & 0x40) != 0)));
if more {
byte |= 0x80; // Mark this byte to show that more bytes will follow.

View File

@ -60,8 +60,8 @@ impl error::Error for Error {
fn cause(&self) -> Option<&dyn error::Error> {
use self::Error::*;
match self {
&IoError(ref e) => Some(e),
match *self {
IoError(ref e) => Some(e),
_ => None,
}
}
@ -70,10 +70,10 @@ impl error::Error for Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match self {
&TermUnset => Ok(()),
&MalformedTerminfo(ref e) => e.fmt(f),
&IoError(ref e) => e.fmt(f),
match *self {
TermUnset => Ok(()),
MalformedTerminfo(ref e) => e.fmt(f),
IoError(ref e) => e.fmt(f),
}
}
}
@ -109,9 +109,9 @@ impl TermInfo {
}
// Keep the metadata small
fn _from_path(path: &Path) -> Result<TermInfo, Error> {
let file = File::open(path).map_err(|e| Error::IoError(e))?;
let file = File::open(path).map_err(Error::IoError)?;
let mut reader = BufReader::new(file);
parse(&mut reader, false).map_err(|e| Error::MalformedTerminfo(e))
parse(&mut reader, false).map_err(Error::MalformedTerminfo)
}
}

View File

@ -12,8 +12,6 @@
use self::Param::*;
use self::States::*;
use self::FormatState::*;
use self::FormatOp::*;
use std::iter::repeat;
@ -36,9 +34,9 @@ enum States {
#[derive(Copy, PartialEq, Clone)]
enum FormatState {
FormatStateFlags,
FormatStateWidth,
FormatStatePrecision,
Flags,
Width,
Precision,
}
/// Types of parameters a capability can use
@ -210,22 +208,22 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result<Vec<
if let Some(arg) = stack.pop() {
let flags = Flags::new();
let res = format(arg, FormatOp::from_char(cur), flags)?;
output.extend(res.iter().map(|x| *x));
output.extend(res.iter().cloned());
} else {
return Err("stack is empty".to_string());
}
}
':' | '#' | ' ' | '.' | '0'..='9' => {
let mut flags = Flags::new();
let mut fstate = FormatStateFlags;
let mut fstate = FormatState::Flags;
match cur {
':' => (),
'#' => flags.alternate = true,
' ' => flags.space = true,
'.' => fstate = FormatStatePrecision,
'.' => fstate = FormatState::Precision,
'0'..='9' => {
flags.width = cur as usize - '0' as usize;
fstate = FormatStateWidth;
fstate = FormatState::Width;
}
_ => unreachable!(),
}
@ -318,43 +316,43 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result<Vec<
(_, 'd') | (_, 'o') | (_, 'x') | (_, 'X') | (_, 's') => {
if let Some(arg) = stack.pop() {
let res = format(arg, FormatOp::from_char(cur), *flags)?;
output.extend(res.iter().map(|x| *x));
output.extend(res.iter().cloned());
// will cause state to go to Nothing
old_state = FormatPattern(*flags, *fstate);
} else {
return Err("stack is empty".to_string());
}
}
(FormatStateFlags, '#') => {
(FormatState::Flags, '#') => {
flags.alternate = true;
}
(FormatStateFlags, '-') => {
(FormatState::Flags, '-') => {
flags.left = true;
}
(FormatStateFlags, '+') => {
(FormatState::Flags, '+') => {
flags.sign = true;
}
(FormatStateFlags, ' ') => {
(FormatState::Flags, ' ') => {
flags.space = true;
}
(FormatStateFlags, '0'..='9') => {
(FormatState::Flags, '0'..='9') => {
flags.width = cur as usize - '0' as usize;
*fstate = FormatStateWidth;
*fstate = FormatState::Width;
}
(FormatStateFlags, '.') => {
*fstate = FormatStatePrecision;
(FormatState::Flags, '.') => {
*fstate = FormatState::Precision;
}
(FormatStateWidth, '0'..='9') => {
(FormatState::Width, '0'..='9') => {
let old = flags.width;
flags.width = flags.width * 10 + (cur as usize - '0' as usize);
if flags.width < old {
return Err("format width overflow".to_string());
}
}
(FormatStateWidth, '.') => {
*fstate = FormatStatePrecision;
(FormatState::Width, '.') => {
*fstate = FormatState::Precision;
}
(FormatStatePrecision, '0'..='9') => {
(FormatState::Precision, '0'..='9') => {
let old = flags.precision;
flags.precision = flags.precision * 10 + (cur as usize - '0' as usize);
if flags.precision < old {
@ -437,31 +435,31 @@ impl Flags {
#[derive(Copy, Clone)]
enum FormatOp {
FormatDigit,
FormatOctal,
FormatHex,
FormatHEX,
FormatString,
Digit,
Octal,
LowerHex,
UpperHex,
String,
}
impl FormatOp {
fn from_char(c: char) -> FormatOp {
match c {
'd' => FormatDigit,
'o' => FormatOctal,
'x' => FormatHex,
'X' => FormatHEX,
's' => FormatString,
'd' => FormatOp::Digit,
'o' => FormatOp::Octal,
'x' => FormatOp::LowerHex,
'X' => FormatOp::UpperHex,
's' => FormatOp::String,
_ => panic!("bad FormatOp char"),
}
}
fn to_char(self) -> char {
match self {
FormatDigit => 'd',
FormatOctal => 'o',
FormatHex => 'x',
FormatHEX => 'X',
FormatString => 's',
FormatOp::Digit => 'd',
FormatOp::Octal => 'o',
FormatOp::LowerHex => 'x',
FormatOp::UpperHex => 'X',
FormatOp::String => 's',
}
}
}
@ -470,7 +468,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8>, String> {
let mut s = match val {
Number(d) => {
match op {
FormatDigit => {
FormatOp::Digit => {
if flags.sign {
format!("{:+01$}", d, flags.precision)
} else if d < 0 {
@ -482,7 +480,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8>, String> {
format!("{:01$}", d, flags.precision)
}
}
FormatOctal => {
FormatOp::Octal => {
if flags.alternate {
// Leading octal zero counts against precision.
format!("0{:01$o}", d, flags.precision.saturating_sub(1))
@ -490,27 +488,27 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8>, String> {
format!("{:01$o}", d, flags.precision)
}
}
FormatHex => {
FormatOp::LowerHex => {
if flags.alternate && d != 0 {
format!("0x{:01$x}", d, flags.precision)
} else {
format!("{:01$x}", d, flags.precision)
}
}
FormatHEX => {
FormatOp::UpperHex => {
if flags.alternate && d != 0 {
format!("0X{:01$X}", d, flags.precision)
} else {
format!("{:01$X}", d, flags.precision)
}
}
FormatString => return Err("non-number on stack with %s".to_string()),
FormatOp::String => return Err("non-number on stack with %s".to_string()),
}
.into_bytes()
}
Words(s) => {
match op {
FormatString => {
FormatOp::String => {
let mut s = s.into_bytes();
if flags.precision > 0 && flags.precision < s.len() {
s.truncate(flags.precision);

View File

@ -198,11 +198,11 @@ impl<T: Write + Send + 'static> Terminal for WinConsole<T> {
Ok(true)
}
fn get_ref<'a>(&'a self) -> &'a T {
fn get_ref(&self) -> &T {
&self.buf
}
fn get_mut<'a>(&'a mut self) -> &'a mut T {
fn get_mut(&mut self) -> &mut T {
&mut self.buf
}