Fix up almost all reported clippyisms

This commit is contained in:
Tony Garnock-Jones 2021-03-12 10:59:28 +01:00
parent bddb111f87
commit d811032ac7
13 changed files with 67 additions and 86 deletions

View File

@ -88,7 +88,7 @@ impl std::fmt::Display for Error {
//---------------------------------------------------------------------------
pub fn is_io_error(e: &Error) -> bool {
if let Error::Io(_) = e { true } else { false }
matches!(e, Error::Io(_))
}
pub fn eof() -> Error {
@ -122,10 +122,7 @@ pub fn io_eof() -> std::io::Error {
}
pub fn is_eof_io_error(e: &std::io::Error) -> bool {
match e.kind() {
std::io::ErrorKind::UnexpectedEof => true,
_ => false,
}
matches!(e.kind(), std::io::ErrorKind::UnexpectedEof)
}
pub fn io_syntax_error(s: &str) -> std::io::Error {
@ -133,8 +130,5 @@ pub fn io_syntax_error(s: &str) -> std::io::Error {
}
pub fn is_syntax_io_error(e: &std::io::Error) -> bool {
match e.kind() {
std::io::ErrorKind::InvalidData => true,
_ => false,
}
matches!(e.kind(), std::io::ErrorKind::InvalidData)
}

View File

@ -167,7 +167,7 @@ mod value_tests {
assert!(f.is_float());
*(f.as_float_mut().unwrap()) = 123.45;
assert_eq!(f, VV::from(123.45f32));
assert_eq!(f.as_float().unwrap(), 123.45f32);
assert_eq!((f.as_float().unwrap() - 123.45f32).abs() < std::f32::EPSILON, true);
}
#[test] fn double_mut() {
@ -175,7 +175,7 @@ mod value_tests {
assert!(f.is_double());
*(f.as_double_mut().unwrap()) = 123.45;
assert_eq!(f, VV::from(123.45));
assert_eq!(f.as_double().unwrap(), 123.45);
assert_eq!((f.as_double().unwrap() - 123.45).abs() < std::f64::EPSILON, true);
}
#[test] fn signedinteger_mut() {
@ -253,8 +253,8 @@ mod decoder_tests {
}
#[test] fn skip_annotations_noskip() {
let mut buf = &b"\x85\x92\x91"[..];
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&mut buf));
let buf = &b"\x85\x92\x91"[..];
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&buf));
let v = d.demand_next().unwrap();
assert_eq!(v.annotations().slice().len(), 1);
assert_eq!(v.annotations().slice()[0], Value::from(2).wrap());
@ -262,8 +262,8 @@ mod decoder_tests {
}
#[test] fn skip_annotations_skip() {
let mut buf = &b"\x85\x92\x91"[..];
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&mut buf));
let buf = &b"\x85\x92\x91"[..];
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&buf));
d.set_read_annotations(false);
let v = d.demand_next().unwrap();
assert_eq!(v.annotations().slice().len(), 0);
@ -271,9 +271,9 @@ mod decoder_tests {
}
#[test] fn multiple_values_buf_advanced() {
let mut buf = &b"\xb4\xb3\x04Ping\x84\xb4\xb3\x04Pong\x84"[..];
let buf = &b"\xb4\xb3\x04Ping\x84\xb4\xb3\x04Pong\x84"[..];
assert_eq!(buf.len(), 16);
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&mut buf));
let mut d = ConfiguredReader::new(PackedReader::decode_bytes(&buf));
assert_eq!(d.reader.source.index, 0);
assert_eq!(d.demand_next().unwrap().value(), &Value::simple_record0("Ping"));
assert_eq!(d.reader.source.index, 8);

View File

@ -8,9 +8,7 @@ where
T: IntoIterator<Item = Item>,
Item: Serialize,
{
let s = s.into_iter()
.map(|item| to_value(item))
.collect::<value::Set<IOValue>>();
let s = s.into_iter().map(to_value).collect::<value::Set<IOValue>>();
UnwrappedIOValue::from(s).wrap().serialize(serializer)
}

View File

@ -35,6 +35,5 @@ pub use value::EMPTY_SEQ;
pub fn invert_map<A, B>(m: &Map<A, B>) -> Map<B, A>
where A: Clone, B: Clone + Ord
{
use std::iter::FromIterator;
Map::from_iter(m.iter().map(|(a, b)| (b.clone(), a.clone())))
m.iter().map(|(a, b)| (b.clone(), a.clone())).collect()
}

View File

@ -27,7 +27,7 @@ pub struct InvalidTag(u8);
impl From<InvalidTag> for std::io::Error {
fn from(v: InvalidTag) -> Self {
std::io::Error::new(std::io::ErrorKind::InvalidData,
format!("Invalid Preserves tag {}", v.0).to_string())
format!("Invalid Preserves tag {}", v.0))
}
}

View File

@ -79,8 +79,8 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
let mut acc: usize = 0;
loop {
let v = self.read()?;
acc = acc | (((v & 0x7f) as usize) << shift);
shift = shift + 7;
acc |= ((v & 0x7f) as usize) << shift;
shift += 7;
if v & 0x80 == 0 { return Ok(acc) }
}
}
@ -130,7 +130,7 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
fn read_signed_integer(&mut self, count: usize) -> IOResult<SignedInteger> {
if count == 0 {
return Ok(SignedInteger::from(0 as i128));
return Ok(SignedInteger::from(0_i128));
}
if count > 16 {
@ -138,7 +138,7 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
if (bs[0] & 0x80) == 0 {
// Positive or zero.
let mut i = 0;
while i < count && bs[i] == 0 { i = i + 1; }
while i < count && bs[i] == 0 { i += 1; }
if count - i <= 16 {
Ok(SignedInteger::from(u128::from_be_bytes(bs[bs.len() - 16..].try_into().unwrap())))
} else {
@ -147,7 +147,7 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
} else {
// Negative.
let mut i = 0;
while i < count && bs[i] == 0xff { i = i + 1; }
while i < count && bs[i] == 0xff { i += 1; }
if count - i <= 16 {
Ok(SignedInteger::from(i128::from_be_bytes(bs[bs.len() - 16..].try_into().unwrap())))
} else {
@ -181,14 +181,14 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
Tag::MediumInteger(count) => {
self.skip()?;
let n = &self.read_signed_integer(count.into())?;
let i = n.try_into().or_else(|_| Err(out_of_range(n)))?;
let i = n.try_into().map_err(|_| out_of_range(n))?;
f(i).ok_or_else(|| out_of_range(i))
}
Tag::SignedInteger => {
self.skip()?;
let count = self.varint()?;
let n = &self.read_signed_integer(count)?;
let i = n.try_into().or_else(|_| Err(out_of_range(n)))?;
let i = n.try_into().map_err(|_| out_of_range(n))?;
f(i).ok_or_else(|| out_of_range(i))
}
_ => Err(self.expected(ExpectedKind::SignedInteger))
@ -208,14 +208,14 @@ impl<'de, S: BinarySource<'de>> PackedReader<'de, S> {
Tag::MediumInteger(count) => {
self.skip()?;
let n = &self.read_signed_integer(count.into())?;
let i = n.try_into().or_else(|_| Err(out_of_range(n)))?;
let i = n.try_into().map_err(|_| out_of_range(n))?;
f(i).ok_or_else(|| out_of_range(i))
}
Tag::SignedInteger => {
self.skip()?;
let count = self.varint()?;
let n = &self.read_signed_integer(count)?;
let i = n.try_into().or_else(|_| Err(out_of_range(n)))?;
let i = n.try_into().map_err(|_| out_of_range(n))?;
f(i).ok_or_else(|| out_of_range(i))
}
_ => Err(self.expected(ExpectedKind::SignedInteger))
@ -294,7 +294,7 @@ impl<'de, S: BinarySource<'de>> Reader<'de> for PackedReader<'de, S> {
Tag::Record => {
let iter = DelimitedStream { reader: self.configured(read_annotations) };
let vs = iter.collect::<IOResult<Vec<IOValue>>>()?;
if vs.len() < 1 {
if vs.is_empty() {
return Err(io_syntax_error("Too few elements in encoded record"))
}
Value::Record(Record(vs)).wrap()
@ -455,11 +455,11 @@ impl<'a, 'de, S: BinarySource<'de>> Iterator for DelimitedStream<'a, 'de, S>
}
}
fn decodestr<'de>(cow: Cow<'de, [u8]>) -> IOResult<Cow<'de, str>> {
fn decodestr(cow: Cow<'_, [u8]>) -> IOResult<Cow<'_, str>> {
match cow {
Cow::Borrowed(bs) =>
Ok(Cow::Borrowed(std::str::from_utf8(bs).map_err(|_| io_syntax_error("Invalid UTF-8"))?)),
Cow::Owned(bs) =>
Ok(Cow::Owned(String::from_utf8(bs).map_err(|_| io_syntax_error("Invalid UTF-8"))?.to_owned())),
Ok(Cow::Owned(String::from_utf8(bs).map_err(|_| io_syntax_error("Invalid UTF-8"))?)),
}
}

View File

@ -1,4 +1,3 @@
use num;
use num::bigint::BigInt;
use num::cast::ToPrimitive;
use std::convert::TryInto;
@ -94,7 +93,7 @@ impl<W: std::io::Write> PackedWriter<W> {
pub fn write_medium_integer(&mut self, bs: &[u8]) -> Result<()> {
let count: u8 = bs.len().try_into().unwrap();
if count > 16 || count < 1 { panic!("Invalid medium_integer count: {}", count) }
if !(1..=16).contains(&count) { panic!("Invalid medium_integer count: {}", count) }
self.write_byte(Tag::MediumInteger(count).into())?;
self.w().write_all(bs)
}
@ -142,7 +141,7 @@ impl BinaryOrderWriter {
}
fn finish<W: WriteWriter>(mut self, w: &mut W) -> Result<()> {
if self.buffer().len() != 0 { panic!("Missing final delimit()"); }
if !self.buffer().is_empty() { panic!("Missing final delimit()"); }
self.items_mut().pop();
self.items_mut().sort();
for bs in self.items() {

View File

@ -27,7 +27,7 @@ pub trait Reader<'de> {
}
fn demand_next(&mut self, read_annotations: bool) -> IOResult<IOValue> {
self.next(read_annotations)?.ok_or_else(|| io_eof())
self.next(read_annotations)?.ok_or_else(io_eof)
}
fn next_boolean(&mut self) -> ReaderResult<bool> { self.demand_next(false)?.value().to_boolean() }
@ -175,7 +175,7 @@ impl<'a, R: Read> IOBinarySource<'a, R> {
impl<'de, 'a, R: Read> BinarySource<'de> for IOBinarySource<'a, R> {
fn skip(&mut self) -> IOResult<()> {
if let None = self.buf { unreachable!(); }
if self.buf.is_none() { unreachable!(); }
self.buf = None;
Ok(())
}
@ -198,14 +198,14 @@ impl<'de, 'a, R: Read> BinarySource<'de> for IOBinarySource<'a, R> {
}
fn readbytes(&mut self, count: usize) -> IOResult<Cow<'de, [u8]>> {
if let Some(_) = self.buf { unreachable!(); }
if self.buf.is_some() { unreachable!(); }
let mut bs = vec![0; count];
self.read.read_exact(&mut bs)?;
Ok(Cow::Owned(bs))
}
fn readbytes_into(&mut self, bs: &mut [u8]) -> IOResult<()> {
if let Some(_) = self.buf { unreachable!(); }
if self.buf.is_some() { unreachable!(); }
self.read.read_exact(bs)
}
}

View File

@ -211,13 +211,14 @@ impl serde::ser::SerializeMap for SerializeDictionary {
}
impl SerializeRecord {
fn push(&mut self, value: IOValue) -> Result<()> {
self.r.fields_vec_mut().push(value);
Ok(())
fn push<T: ?Sized>(&mut self, value: &T)
where T: Serialize
{
self.r.fields_vec_mut().push(to_value(value))
}
fn finish(self) -> Result<IOValue> {
Ok(self.r.finish().wrap())
fn finish(self) -> IOValue {
self.r.finish().wrap()
}
}
@ -228,11 +229,12 @@ impl serde::ser::SerializeStruct for SerializeRecord {
fn serialize_field<T: ?Sized>(&mut self, _name: &'static str, value: &T) -> Result<()>
where T: Serialize
{
self.push(to_value(value))
self.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok> {
self.finish()
Ok(self.finish())
}
}
@ -243,11 +245,12 @@ impl serde::ser::SerializeStructVariant for SerializeRecord {
fn serialize_field<T: ?Sized>(&mut self, _name: &'static str, value: &T) -> Result<()>
where T: Serialize
{
self.push(to_value(value))
self.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok> {
self.finish()
Ok(self.finish())
}
}
@ -256,11 +259,12 @@ impl serde::ser::SerializeTuple for SerializeRecord {
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
self.push(to_value(value))
self.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok> {
self.finish()
Ok(self.finish())
}
}
@ -269,11 +273,12 @@ impl serde::ser::SerializeTupleStruct for SerializeRecord {
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
self.push(to_value(value))
self.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok> {
self.finish()
Ok(self.finish())
}
}
@ -282,11 +287,12 @@ impl serde::ser::SerializeTupleVariant for SerializeRecord {
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> where T: Serialize {
self.push(to_value(value))
self.push(value);
Ok(())
}
fn end(self) -> Result<Self::Ok> {
self.finish()
Ok(self.finish())
}
}

View File

@ -63,24 +63,15 @@ impl SignedInteger {
}
pub fn is_i(&self) -> bool {
match self.repr() {
SignedIntegerRepr::I128(_) => true,
_ => false,
}
matches!(self.0, SignedIntegerRepr::I128(_))
}
pub fn is_u(&self) -> bool {
match self.0 {
SignedIntegerRepr::U128(_) => true,
_ => false,
}
matches!(self.0, SignedIntegerRepr::U128(_))
}
pub fn is_big(&self) -> bool {
match self.0 {
SignedIntegerRepr::Big(_) => true,
_ => false,
}
matches!(self.0, SignedIntegerRepr::Big(_))
}
}

View File

@ -487,7 +487,7 @@ impl<N: NestedValue<D>, D: Domain> Value<N, D> {
pub fn to_char(&self) -> Result<char, Error> {
let fs = self.to_simple_record("UnicodeScalar", Some(1))?;
let c = fs[0].value().to_u32()?;
char::try_from(c).or_else(|_| Err(Error::InvalidUnicodeScalar(c)))
char::try_from(c).map_err(|_| Error::InvalidUnicodeScalar(c))
}
pub fn is_string(&self) -> bool {
@ -573,11 +573,7 @@ impl<N: NestedValue<D>, D: Domain> Value<N, D> {
}
pub fn is_record(&self) -> bool {
if let Value::Record(_) = *self {
true
} else {
false
}
matches!(*self, Value::Record(_))
}
pub fn as_record(&self, arity: Option<usize>) -> Option<&Record<N>> {
@ -799,7 +795,7 @@ pub fn deserialize_nested_value<'de, D, N, Dom: Domain>(deserializer: D) ->
//---------------------------------------------------------------------------
#[derive(Clone)]
pub struct Annotations<N: NestedValue<D>, D: Domain>(Option<Box<Vec<N>>>, PhantomData<D>);
pub struct Annotations<N: NestedValue<D>, D: Domain>(Option<Vec<N>>, PhantomData<D>);
impl<N: NestedValue<D>, D: Domain> Annotations<N, D> {
pub fn empty() -> Self {
@ -808,8 +804,7 @@ impl<N: NestedValue<D>, D: Domain> Annotations<N, D> {
}
pub fn new(anns: Option<Vec<N>>) -> Self {
Annotations(anns.and_then(|v| if v.is_empty() { None } else { Some(Box::new(v)) }),
PhantomData)
Annotations(anns, PhantomData)
}
pub fn maybe_slice(&self) -> Option<&[N]> {
@ -827,9 +822,9 @@ impl<N: NestedValue<D>, D: Domain> Annotations<N, D> {
where
F: FnOnce(&mut Vec<N>)
{
let mut v: Vec<N> = self.0.take().map_or_else(|| vec![], |b| *b);
let mut v: Vec<N> = self.0.take().unwrap_or_else(Vec::new);
f(&mut v);
self.0 = if v.is_empty() { None } else { Some(Box::new(v)) };
self.0 = if v.is_empty() { None } else { Some(v) };
self
}
@ -841,7 +836,7 @@ impl<N: NestedValue<D>, D: Domain> Annotations<N, D> {
None =>
Annotations(None, PhantomData),
Some(ref b) =>
Annotations(Some(Box::new(b.iter().map(|a| a.copy_via(f)).collect())), PhantomData),
Annotations(Some(b.iter().map(|a| a.copy_via(f)).collect()), PhantomData),
}
}
}

View File

@ -1,4 +1,3 @@
use num;
use num::bigint::BigInt;
use std::io::Error;
use super::signed_integer::SignedIntegerRepr;
@ -145,13 +144,13 @@ pub trait Writer: Sized {
pub fn varint<W: std::io::Write>(w: &mut W, mut v: u64) -> Result<usize> {
let mut byte_count = 0;
loop {
byte_count = byte_count + 1;
byte_count += 1;
if v < 128 {
w.write_all(&[v as u8])?;
return Ok(byte_count);
} else {
w.write_all(&[((v & 0x7f) + 128) as u8])?;
v = v >> 7;
v >>= 7;
}
}
}

View File

@ -10,7 +10,7 @@ use std::iter::Iterator;
mod samples;
use samples::*;
fn decode_all<'de>(bytes: &'de [u8]) -> Result<Vec<IOValue>, std::io::Error> {
fn decode_all(bytes: &'_ [u8]) -> Result<Vec<IOValue>, std::io::Error> {
PackedReader::decode_bytes(bytes).configured(true).collect()
}
@ -48,7 +48,7 @@ fn decode_all<'de>(bytes: &'de [u8]) -> Result<Vec<IOValue>, std::io::Error> {
match decode_all(&bin[..]) {
Ok(_) => panic!("Unexpected success"),
Err(e) => if is_syntax_io_error(&e) {
()
// all is OK
} else {
panic!("Unexpected error {:?}", e)
}