From d811032ac764179fa26de81211919e2d07f89359 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Fri, 12 Mar 2021 10:59:28 +0100 Subject: [PATCH] Fix up almost all reported clippyisms --- implementations/rust/src/error.rs | 12 ++----- implementations/rust/src/lib.rs | 16 ++++----- implementations/rust/src/set.rs | 4 +-- implementations/rust/src/value/mod.rs | 3 +- .../rust/src/value/packed/constants.rs | 2 +- .../rust/src/value/packed/reader.rs | 24 ++++++------- .../rust/src/value/packed/writer.rs | 5 ++- implementations/rust/src/value/reader.rs | 8 ++--- implementations/rust/src/value/ser.rs | 36 +++++++++++-------- .../rust/src/value/signed_integer.rs | 15 ++------ implementations/rust/src/value/value.rs | 19 ++++------ implementations/rust/src/value/writer.rs | 5 ++- implementations/rust/tests/samples_tests.rs | 4 +-- 13 files changed, 67 insertions(+), 86 deletions(-) diff --git a/implementations/rust/src/error.rs b/implementations/rust/src/error.rs index 721dc37..2648f92 100644 --- a/implementations/rust/src/error.rs +++ b/implementations/rust/src/error.rs @@ -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) } diff --git a/implementations/rust/src/lib.rs b/implementations/rust/src/lib.rs index 635680b..eb83450 100644 --- a/implementations/rust/src/lib.rs +++ b/implementations/rust/src/lib.rs @@ -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); diff --git a/implementations/rust/src/set.rs b/implementations/rust/src/set.rs index 0286a3b..5203002 100644 --- a/implementations/rust/src/set.rs +++ b/implementations/rust/src/set.rs @@ -8,9 +8,7 @@ where T: IntoIterator, Item: Serialize, { - let s = s.into_iter() - .map(|item| to_value(item)) - .collect::>(); + let s = s.into_iter().map(to_value).collect::>(); UnwrappedIOValue::from(s).wrap().serialize(serializer) } diff --git a/implementations/rust/src/value/mod.rs b/implementations/rust/src/value/mod.rs index 2ad25fa..b12c8d4 100644 --- a/implementations/rust/src/value/mod.rs +++ b/implementations/rust/src/value/mod.rs @@ -35,6 +35,5 @@ pub use value::EMPTY_SEQ; pub fn invert_map(m: &Map) -> Map 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() } diff --git a/implementations/rust/src/value/packed/constants.rs b/implementations/rust/src/value/packed/constants.rs index ea93806..716cb8f 100644 --- a/implementations/rust/src/value/packed/constants.rs +++ b/implementations/rust/src/value/packed/constants.rs @@ -27,7 +27,7 @@ pub struct InvalidTag(u8); impl From 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)) } } diff --git a/implementations/rust/src/value/packed/reader.rs b/implementations/rust/src/value/packed/reader.rs index 3da0cd4..2fc306f 100644 --- a/implementations/rust/src/value/packed/reader.rs +++ b/implementations/rust/src/value/packed/reader.rs @@ -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 { 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::>>()?; - 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> { +fn decodestr(cow: Cow<'_, [u8]>) -> IOResult> { 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"))?)), } } diff --git a/implementations/rust/src/value/packed/writer.rs b/implementations/rust/src/value/packed/writer.rs index 9850571..0296dac 100644 --- a/implementations/rust/src/value/packed/writer.rs +++ b/implementations/rust/src/value/packed/writer.rs @@ -1,4 +1,3 @@ -use num; use num::bigint::BigInt; use num::cast::ToPrimitive; use std::convert::TryInto; @@ -94,7 +93,7 @@ impl PackedWriter { 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(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() { diff --git a/implementations/rust/src/value/reader.rs b/implementations/rust/src/value/reader.rs index ebc1891..29793dd 100644 --- a/implementations/rust/src/value/reader.rs +++ b/implementations/rust/src/value/reader.rs @@ -27,7 +27,7 @@ pub trait Reader<'de> { } fn demand_next(&mut self, read_annotations: bool) -> IOResult { - self.next(read_annotations)?.ok_or_else(|| io_eof()) + self.next(read_annotations)?.ok_or_else(io_eof) } fn next_boolean(&mut self) -> ReaderResult { 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> { - 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) } } diff --git a/implementations/rust/src/value/ser.rs b/implementations/rust/src/value/ser.rs index 215b56e..c0c4f40 100644 --- a/implementations/rust/src/value/ser.rs +++ b/implementations/rust/src/value/ser.rs @@ -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(&mut self, value: &T) + where T: Serialize + { + self.r.fields_vec_mut().push(to_value(value)) } - fn finish(self) -> Result { - 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(&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.finish() + Ok(self.finish()) } } @@ -243,11 +245,12 @@ impl serde::ser::SerializeStructVariant for SerializeRecord { fn serialize_field(&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.finish() + Ok(self.finish()) } } @@ -256,11 +259,12 @@ impl serde::ser::SerializeTuple for SerializeRecord { type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<()> where T: Serialize { - self.push(to_value(value)) + self.push(value); + Ok(()) } fn end(self) -> Result { - self.finish() + Ok(self.finish()) } } @@ -269,11 +273,12 @@ impl serde::ser::SerializeTupleStruct for SerializeRecord { type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<()> where T: Serialize { - self.push(to_value(value)) + self.push(value); + Ok(()) } fn end(self) -> Result { - self.finish() + Ok(self.finish()) } } @@ -282,11 +287,12 @@ impl serde::ser::SerializeTupleVariant for SerializeRecord { type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<()> where T: Serialize { - self.push(to_value(value)) + self.push(value); + Ok(()) } fn end(self) -> Result { - self.finish() + Ok(self.finish()) } } diff --git a/implementations/rust/src/value/signed_integer.rs b/implementations/rust/src/value/signed_integer.rs index d4d3026..4d38dd7 100644 --- a/implementations/rust/src/value/signed_integer.rs +++ b/implementations/rust/src/value/signed_integer.rs @@ -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(_)) } } diff --git a/implementations/rust/src/value/value.rs b/implementations/rust/src/value/value.rs index c0613b7..4e16924 100644 --- a/implementations/rust/src/value/value.rs +++ b/implementations/rust/src/value/value.rs @@ -487,7 +487,7 @@ impl, D: Domain> Value { pub fn to_char(&self) -> Result { 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, D: Domain> Value { } 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) -> Option<&Record> { @@ -799,7 +795,7 @@ pub fn deserialize_nested_value<'de, D, N, Dom: Domain>(deserializer: D) -> //--------------------------------------------------------------------------- #[derive(Clone)] -pub struct Annotations, D: Domain>(Option>>, PhantomData); +pub struct Annotations, D: Domain>(Option>, PhantomData); impl, D: Domain> Annotations { pub fn empty() -> Self { @@ -808,8 +804,7 @@ impl, D: Domain> Annotations { } pub fn new(anns: Option>) -> 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, D: Domain> Annotations { where F: FnOnce(&mut Vec) { - let mut v: Vec = self.0.take().map_or_else(|| vec![], |b| *b); + let mut v: Vec = 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, D: Domain> Annotations { 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), } } } diff --git a/implementations/rust/src/value/writer.rs b/implementations/rust/src/value/writer.rs index 5a05560..6aecddf 100644 --- a/implementations/rust/src/value/writer.rs +++ b/implementations/rust/src/value/writer.rs @@ -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: &mut W, mut v: u64) -> Result { 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; } } } diff --git a/implementations/rust/tests/samples_tests.rs b/implementations/rust/tests/samples_tests.rs index 45084b8..3a09041 100644 --- a/implementations/rust/tests/samples_tests.rs +++ b/implementations/rust/tests/samples_tests.rs @@ -10,7 +10,7 @@ use std::iter::Iterator; mod samples; use samples::*; -fn decode_all<'de>(bytes: &'de [u8]) -> Result, std::io::Error> { +fn decode_all(bytes: &'_ [u8]) -> Result, std::io::Error> { PackedReader::decode_bytes(bytes).configured(true).collect() } @@ -48,7 +48,7 @@ fn decode_all<'de>(bytes: &'de [u8]) -> Result, 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) }