Fixed the clippy Eq warning. (#574)

Added DecodeError::Io
Removed `PartialEq` on DecodeError
This commit is contained in:
Trangar 2022-08-18 15:57:18 +02:00 committed by GitHub
parent 035baf735f
commit 974abe8661
14 changed files with 99 additions and 68 deletions

View File

@ -8,7 +8,7 @@ use std::collections::BTreeSet;
type NodeId = u64; type NodeId = u64;
#[derive( #[derive(
bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, Debug, PartialEq, bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq,
)] )]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub struct Membership { pub struct Membership {

View File

@ -5,7 +5,7 @@
use rand::Rng; use rand::Rng;
#[derive( #[derive(
Debug, bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, PartialEq, Debug, bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, PartialEq, Eq,
)] )]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub struct Lcg64Xsh32 { pub struct Lcg64Xsh32 {

View File

@ -25,7 +25,7 @@ fn random(rng: &mut impl Rng) -> FTXresponse<Trade> {
} }
} }
#[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq)] #[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub enum FTXresponse<T> { pub enum FTXresponse<T> {
Result(FTXresponseSuccess<T>), Result(FTXresponseSuccess<T>),
@ -33,7 +33,7 @@ pub enum FTXresponse<T> {
} }
#[derive( #[derive(
bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, Debug, PartialEq, bincode_2::Encode, bincode_2::Decode, serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq,
)] )]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub struct FTXresponseSuccess<T> { pub struct FTXresponseSuccess<T> {
@ -41,14 +41,14 @@ pub struct FTXresponseSuccess<T> {
pub result: T, pub result: T,
} }
#[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq)] #[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub struct FTXresponseFailure { pub struct FTXresponseFailure {
pub success: bool, pub success: bool,
pub error: String, pub error: String,
} }
#[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq)] #[derive(bincode_2::Encode, bincode_2::Decode, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[bincode(crate = "bincode_2")] #[bincode(crate = "bincode_2")]
pub enum TradeSide { pub enum TradeSide {
Buy, Buy,

View File

@ -65,7 +65,7 @@ impl core::fmt::Display for EncodeError {
/// Errors that can be encountered by decoding a type /// Errors that can be encountered by decoding a type
#[non_exhaustive] #[non_exhaustive]
#[derive(Debug, PartialEq)] #[derive(Debug)]
pub enum DecodeError { pub enum DecodeError {
/// The reader reached its end but more bytes were expected. /// The reader reached its end but more bytes were expected.
UnexpectedEnd { UnexpectedEnd {
@ -164,6 +164,20 @@ pub enum DecodeError {
position: usize, position: usize,
}, },
/// The reader encountered an IO error but more bytes were expected.
#[cfg(feature = "std")]
Io {
/// The IO error expected
inner: std::io::Error,
/// Gives an estimate of how many extra bytes are needed.
///
/// **Note**: this is only an estimate and not indicative of the actual bytes needed.
///
/// **Note**: Bincode has no look-ahead mechanism. This means that this will only return the amount of bytes to be read for the current action, and not take into account the entire data structure being read.
additional: usize,
},
/// An uncommon error occurred, see the inner text for more information /// An uncommon error occurred, see the inner text for more information
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
OtherString(alloc::string::String), OtherString(alloc::string::String),
@ -199,7 +213,7 @@ impl DecodeError {
/// Indicates which enum variants are allowed /// Indicates which enum variants are allowed
#[non_exhaustive] #[non_exhaustive]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Eq)]
pub enum AllowedEnumVariants { pub enum AllowedEnumVariants {
/// All values between `min` and `max` (inclusive) are allowed /// All values between `min` and `max` (inclusive) are allowed
#[allow(missing_docs)] #[allow(missing_docs)]

View File

@ -48,12 +48,12 @@ where
{ {
#[inline(always)] #[inline(always)]
fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> { fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> {
match self.reader.read_exact(bytes) { self.reader
Ok(_) => Ok(()), .read_exact(bytes)
Err(_) => Err(DecodeError::UnexpectedEnd { .map_err(|inner| DecodeError::Io {
inner,
additional: bytes.len(), additional: bytes.len(),
}), })
}
} }
} }
@ -62,12 +62,10 @@ where
R: std::io::Read, R: std::io::Read,
{ {
fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> { fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> {
match self.read_exact(bytes) { self.read_exact(bytes).map_err(|inner| DecodeError::Io {
Ok(_) => Ok(()), inner,
Err(_) => Err(DecodeError::UnexpectedEnd { additional: bytes.len(),
additional: bytes.len(), })
}),
}
} }
#[inline] #[inline]

View File

@ -65,7 +65,7 @@ pub use self::de_owned::*;
pub use self::ser::*; pub use self::ser::*;
/// A serde-specific error that occurred while decoding. /// A serde-specific error that occurred while decoding.
#[derive(Debug, PartialEq)] #[derive(Debug)]
#[non_exhaustive] #[non_exhaustive]
pub enum DecodeError { pub enum DecodeError {
/// Bincode does not support serde's `any` decoding feature /// Bincode does not support serde's `any` decoding feature
@ -124,7 +124,7 @@ impl Into<crate::error::DecodeError> for DecodeError {
} }
/// A serde-specific error that occurred while encoding. /// A serde-specific error that occurred while encoding.
#[derive(Debug, PartialEq)] #[derive(Debug)]
#[non_exhaustive] #[non_exhaustive]
pub enum EncodeError { pub enum EncodeError {
/// Serde provided bincode with a sequence without a length, which is not supported in bincode /// Serde provided bincode with a sequence without a length, which is not supported in bincode

View File

@ -1,5 +1,6 @@
mod utils; mod utils;
use bincode::error::DecodeError;
use core::cell::{Cell, RefCell}; use core::cell::{Cell, RefCell};
use core::ops::Bound; use core::ops::Bound;
use core::time::Duration; use core::time::Duration;
@ -253,13 +254,14 @@ fn test_duration_out_of_range() {
let result: Result<(std::time::Duration, usize), _> = let result: Result<(std::time::Duration, usize), _> =
bincode::decode_from_slice(&input, bincode::config::standard()); bincode::decode_from_slice(&input, bincode::config::standard());
assert_eq!( match result {
result.unwrap_err(), Err(DecodeError::InvalidDuration {
bincode::error::DecodeError::InvalidDuration {
secs: u64::MAX, secs: u64::MAX,
nanos: u32::MAX nanos: u32::MAX,
} }) => {}
); Err(e) => panic!("Expected InvalidDuration, got {:?}", e),
Ok(_) => panic!("Expected the decode to fail"),
}
} }
#[test] #[test]

View File

@ -1,5 +1,7 @@
#![cfg(feature = "derive")] #![cfg(feature = "derive")]
use bincode::error::DecodeError;
#[derive(bincode::Encode, PartialEq, Debug)] #[derive(bincode::Encode, PartialEq, Debug)]
pub(crate) struct Test<T> { pub(crate) struct Test<T> {
a: T, a: T,
@ -276,28 +278,38 @@ fn test_c_style_enum() {
assert_eq!(ser(CStyleEnum::D), 5); assert_eq!(ser(CStyleEnum::D), 5);
assert_eq!(ser(CStyleEnum::E), 6); assert_eq!(ser(CStyleEnum::E), 6);
fn de(num: u8) -> Result<CStyleEnum, bincode::error::DecodeError> { fn assert_de_successfully(num: u8, expected: CStyleEnum) {
let (result, len) = bincode::decode_from_slice(&[num], bincode::config::standard())?; match bincode::decode_from_slice::<CStyleEnum, _>(&[num], bincode::config::standard()) {
assert_eq!(len, 1); Ok((result, len)) => {
Ok(result) assert_eq!(len, 1);
assert_eq!(result, expected)
}
Err(e) => panic!("Could not deserialize CStyleEnum idx {num}: {e:?}"),
}
} }
fn expected_err(idx: u32) -> Result<CStyleEnum, bincode::error::DecodeError> { fn assert_de_fails(num: u8) {
Err(bincode::error::DecodeError::UnexpectedVariant { match bincode::decode_from_slice::<CStyleEnum, _>(&[num], bincode::config::standard()) {
type_name: "CStyleEnum", Ok(_) => {
allowed: &bincode::error::AllowedEnumVariants::Allowed(&[1, 2, 3, 5, 6]), panic!("Expected to not be able to decode CStyleEnum index {num}, but it succeeded")
found: idx, }
}) Err(DecodeError::UnexpectedVariant {
type_name: "CStyleEnum",
allowed: &bincode::error::AllowedEnumVariants::Allowed(&[1, 2, 3, 5, 6]),
found,
}) if found == num as u32 => {}
Err(e) => panic!("Expected DecodeError::UnexpectedVariant, got {e:?}"),
}
} }
assert_eq!(de(0), expected_err(0)); assert_de_fails(0);
assert_eq!(de(1).unwrap(), CStyleEnum::A); assert_de_successfully(1, CStyleEnum::A);
assert_eq!(de(2).unwrap(), CStyleEnum::B); assert_de_successfully(2, CStyleEnum::B);
assert_eq!(de(3).unwrap(), CStyleEnum::C); assert_de_successfully(3, CStyleEnum::C);
assert_eq!(de(4), expected_err(4)); assert_de_fails(4);
assert_eq!(de(5).unwrap(), CStyleEnum::D); assert_de_successfully(5, CStyleEnum::D);
assert_eq!(de(6).unwrap(), CStyleEnum::E); assert_de_successfully(6, CStyleEnum::E);
assert_eq!(de(7), expected_err(7)); assert_de_fails(7);
} }
macro_rules! macro_newtype { macro_rules! macro_newtype {
@ -344,14 +356,13 @@ pub enum BorrowedEmptyEnum {}
#[test] #[test]
fn test_empty_enum_decode() { fn test_empty_enum_decode() {
let err = match bincode::decode_from_slice::<EmptyEnum, _>(&[], bincode::config::standard()) {
bincode::decode_from_slice::<EmptyEnum, _>(&[], bincode::config::standard()).unwrap_err(); Ok(_) => panic!("We successfully decoded an empty slice, this should never happen"),
assert_eq!( Err(DecodeError::EmptyEnum {
err, type_name: "derive::EmptyEnum",
bincode::error::DecodeError::EmptyEnum { }) => {}
type_name: "derive::EmptyEnum" Err(e) => panic!("Expected DecodeError::EmptyEnum, got {e:?}"),
} }
);
} }
#[derive(bincode::Encode, bincode::Decode, PartialEq, Debug, Eq)] #[derive(bincode::Encode, bincode::Decode, PartialEq, Debug, Eq)]

View File

@ -5,7 +5,7 @@
/// # Remarks /// # Remarks
/// Used to store HID-IO data chunks. Will be chunked into individual packets on transmission. /// Used to store HID-IO data chunks. Will be chunked into individual packets on transmission.
#[repr(C)] #[repr(C)]
#[derive(PartialEq, Clone, Debug, bincode::Encode)] #[derive(PartialEq, Eq, Clone, Debug, bincode::Encode)]
pub struct HidIoPacketBuffer<const H: usize> { pub struct HidIoPacketBuffer<const H: usize> {
/// Type of packet (Continued is automatically set if needed) /// Type of packet (Continued is automatically set if needed)
pub ptype: u32, pub ptype: u32,
@ -20,7 +20,7 @@ pub struct HidIoPacketBuffer<const H: usize> {
} }
#[repr(u32)] #[repr(u32)]
#[derive(PartialEq, Clone, Copy, Debug, bincode::Encode)] #[derive(PartialEq, Eq, Clone, Copy, Debug, bincode::Encode)]
#[allow(dead_code)] #[allow(dead_code)]
/// Requests for to perform a specific action /// Requests for to perform a specific action
pub enum HidIoCommandId { pub enum HidIoCommandId {

View File

@ -8,12 +8,12 @@ use std::collections::HashMap;
use std::prelude::rust_2021::*; use std::prelude::rust_2021::*;
use uuid::Uuid; use uuid::Uuid;
#[derive(serde_derive::Serialize, serde_derive::Deserialize, PartialEq, Debug)] #[derive(serde_derive::Serialize, serde_derive::Deserialize, PartialEq, Eq, Debug)]
pub struct MyStruct { pub struct MyStruct {
name: String, name: String,
} }
#[derive(serde_derive::Serialize, serde_derive::Deserialize, PartialEq, Debug)] #[derive(serde_derive::Serialize, serde_derive::Deserialize, PartialEq, Eq, Debug)]
pub struct CustomerTest { pub struct CustomerTest {
pub id: Option<Uuid>, pub id: Option<Uuid>,
pub email_address: Option<String>, pub email_address: Option<String>,

View File

@ -13,6 +13,7 @@ use std::collections::BTreeSet;
serde_derive::Deserialize, serde_derive::Deserialize,
Debug, Debug,
PartialEq, PartialEq,
Eq,
)] )]
pub struct Membership { pub struct Membership {
/// learners set /// learners set

View File

@ -50,7 +50,7 @@ fn test_serde_round_trip() {
assert_eq!(len, 13); assert_eq!(len, 13);
} }
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct SerdeWithBorrowedData<'a> { pub struct SerdeWithBorrowedData<'a> {
pub a: u32, pub a: u32,
#[serde(skip)] #[serde(skip)]
@ -95,7 +95,7 @@ fn test_serialize_deserialize_borrowed_data() {
); );
} }
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct SerdeWithOwnedData { pub struct SerdeWithOwnedData {
pub a: u32, pub a: u32,
#[serde(skip)] #[serde(skip)]
@ -146,18 +146,18 @@ mod derive {
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct SerdeType { pub struct SerdeType {
pub a: u32, pub a: u32,
} }
#[derive(Decode, Encode, PartialEq, Debug)] #[derive(Decode, Encode, PartialEq, Eq, Debug)]
pub struct StructWithSerde { pub struct StructWithSerde {
#[bincode(with_serde)] #[bincode(with_serde)]
pub serde: SerdeType, pub serde: SerdeType,
} }
#[derive(Decode, Encode, PartialEq, Debug)] #[derive(Decode, Encode, PartialEq, Eq, Debug)]
pub enum EnumWithSerde { pub enum EnumWithSerde {
Unit(#[bincode(with_serde)] SerdeType), Unit(#[bincode(with_serde)] SerdeType),
Struct { Struct {

View File

@ -3,6 +3,7 @@
mod utils; mod utils;
use bincode::error::DecodeError;
use std::{ use std::{
ffi::{CStr, CString}, ffi::{CStr, CString},
io::{Cursor, Seek, SeekFrom}, io::{Cursor, Seek, SeekFrom},
@ -149,12 +150,16 @@ fn test_system_time_out_of_range() {
let result: Result<(std::time::SystemTime, usize), _> = let result: Result<(std::time::SystemTime, usize), _> =
bincode::decode_from_slice(&input, bincode::config::standard()); bincode::decode_from_slice(&input, bincode::config::standard());
assert_eq!( match result {
result.unwrap_err(), Ok(_) => panic!("Expected the decode to fail, but it succeeded"),
bincode::error::DecodeError::InvalidSystemTime { Err(DecodeError::InvalidSystemTime { duration }) => {
duration: std::time::Duration::new(10447520527445462160, 144), assert_eq!(
duration,
std::time::Duration::new(10447520527445462160, 144)
)
} }
); Err(e) => panic!("Expected DecodeError::InvalidSystemTime, got {e:?}"),
}
} }
/// Simple example of user-defined hasher to test encoding/decoding HashMap and HashSet with custom hash algorithms. /// Simple example of user-defined hasher to test encoding/decoding HashMap and HashSet with custom hash algorithms.

View File

@ -42,7 +42,7 @@ where
let mut buffer = [0u8; 2048]; let mut buffer = [0u8; 2048];
let len = bincode::serde::encode_into_slice(&element, &mut buffer, config); let len = bincode::serde::encode_into_slice(&element, &mut buffer, config);
let decoded = bincode::serde::decode_from_slice(&mut buffer, config); let decoded = bincode::serde::decode_from_slice(&buffer, config);
if !C::SKIP_FIXED_ARRAY_LENGTH { if !C::SKIP_FIXED_ARRAY_LENGTH {
let len = len.unwrap(); let len = len.unwrap();