Skip to content
This repository has been archived by the owner on Dec 1, 2023. It is now read-only.

Commit

Permalink
fix: [#9] Clipply errors
Browse files Browse the repository at this point in the history
Some of them were allow:

- #[allow(clippy::extra_unused_lifetimes)]
- #[allow(clippy::cast_possible_wrap)]
- #[allow(clippy::needless_pass_by_value)]

Pending to review.
  • Loading branch information
josecelano committed Sep 25, 2023
1 parent e5bda12 commit b3b2a44
Show file tree
Hide file tree
Showing 14 changed files with 85 additions and 69 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/checking.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ env:

jobs:
check:
name: Static Analysis
name: Checking
runs-on: ubuntu-latest

strategy:
Expand All @@ -34,11 +34,11 @@ jobs:

- id: check
name: Run Build Checks
run: cargo check --tests --benches --examples --workspace --all-targets --all-features
run: cargo check --tests --examples --workspace --all-features

- id: lint
name: Run Lint Checks
run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic
run: cargo clippy --tests --examples --workspace --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic

- id: doc
name: Run Documentation Checks
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/testing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ env:

jobs:
test:
name: Units
name: Testing
runs-on: ubuntu-latest

strategy:
Expand All @@ -34,4 +34,4 @@ jobs:

- id: test
name: Run Unit Tests
run: cargo test --tests --benches --examples --workspace --all-targets --all-features
run: cargo test --tests --examples --workspace --all-features
2 changes: 0 additions & 2 deletions benches/benches.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#![feature(test)]

extern crate serde;
extern crate test;
#[macro_use]
extern crate serde_derive;
extern crate torrust_serde_bencode;

use serde::Serialize;
use test::Bencher;
Expand Down
7 changes: 6 additions & 1 deletion cSpell.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
{
"words": [
"bencoded",
"Calisota",
"Duckburg",
"httpseeds",
"Serde"
"libfuzzer",
"newtype",
"Serde",
"Walke"
],
"enableFiletypes": [
"dockerfile",
Expand Down
4 changes: 2 additions & 2 deletions examples/parse_torrent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ fn main() {
match handle.read_to_end(&mut buffer) {
Ok(_) => match de::from_bytes::<Torrent>(&buffer) {
Ok(t) => render_torrent(&t),
Err(e) => println!("ERROR: {:?}", e),
Err(e) => println!("ERROR: {e:?}"),
},
Err(e) => println!("ERROR: {:?}", e),
Err(e) => println!("ERROR: {e:?}"),
}
}
4 changes: 2 additions & 2 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "serde_bencode-fuzz"
name = "torrust_serde_bencode_fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
Expand All @@ -11,7 +11,7 @@ cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"

[dependencies.serde_bencode]
[dependencies.torrust_serde_bencode]
path = ".."

# Prevent this from interfering with workspaces
Expand Down
4 changes: 2 additions & 2 deletions fuzz/fuzz_targets/from_bytes.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#![no_main]
use libfuzzer_sys::fuzz_target;

use serde_bencode::value::Value;
use serde_bencode::from_bytes;
use torrust_serde_bencode::from_bytes;
use torrust_serde_bencode::value::Value;

fuzz_target!(|data: &[u8]| {
let _: Result<Value, _> = from_bytes(data);
Expand Down
24 changes: 12 additions & 12 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ impl<'de, 'a, R: 'a + Read> de::EnumAccess<'de> for BencodeAccess<'a, R> {
}
ParseResult::Map => Ok((seed.deserialize(&mut *self.de)?, self)),
t => Err(Error::InvalidValue(format!(
"Expected bytes or map; got `{:?}`",
t
"Expected bytes or map; got `{t:?}`"
))),
}
}
Expand All @@ -146,7 +145,7 @@ impl ParseResult {
Self::Bytes(bytes) => Error::invalid_type(Unexpected::Bytes(bytes), &expected),
Self::List => Error::invalid_type(Unexpected::Seq, &expected),
Self::Map => Error::invalid_type(Unexpected::Map, &expected),
Self::End => Error::custom(format_args!("unexpected end, expected {}", expected)),
Self::End => Error::custom(format_args!("unexpected end, expected {expected}")),
}
}
}
Expand All @@ -158,6 +157,7 @@ pub struct Deserializer<R: Read> {
next: Option<ParseResult>,
}

#[allow(clippy::extra_unused_lifetimes)]
impl<'de, R: Read> Deserializer<R> {
/// Create a new deserializer.
pub fn new(reader: R) -> Deserializer<R> {
Expand All @@ -177,7 +177,7 @@ impl<'de, R: Read> Deserializer<R> {
Error::InvalidValue("Non UTF-8 integer encoding".to_string())
})?;
let len_int = len_str.parse().map_err(|_| {
Error::InvalidValue(format!("Can't parse `{}` as integer", len_str))
Error::InvalidValue(format!("Can't parse `{len_str}` as integer"))
})?;
return Ok(len_int);
}
Expand All @@ -200,7 +200,7 @@ impl<'de, R: Read> Deserializer<R> {
Error::InvalidValue("Non UTF-8 integer encoding".to_string())
})?;
let len_int = len_str.parse().map_err(|_| {
Error::InvalidValue(format!("Can't parse `{}` as string length", len_str))
Error::InvalidValue(format!("Can't parse `{len_str}` as string length"))
})?;
return Ok(len_int);
}
Expand Down Expand Up @@ -255,12 +255,12 @@ impl<'de, 'a, R: Read> de::Deserializer<'de> for &'a mut Deserializer<R> {
type Error = Error;

#[inline]
fn deserialize_any<V: de::Visitor<'de>>(mut self, visitor: V) -> Result<V::Value> {
fn deserialize_any<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
match self.parse()? {
ParseResult::Int(i) => visitor.visit_i64(i),
ParseResult::Bytes(s) => visitor.visit_bytes(s.as_ref()),
ParseResult::List => visitor.visit_seq(BencodeAccess::new(&mut self, None)),
ParseResult::Map => visitor.visit_map(BencodeAccess::new(&mut self, None)),
ParseResult::List => visitor.visit_seq(BencodeAccess::new(self, None)),
ParseResult::Map => visitor.visit_map(BencodeAccess::new(self, None)),
ParseResult::End => Err(Error::EndOfStream),
}
}
Expand Down Expand Up @@ -345,7 +345,7 @@ impl<'de, 'a, R: Read> de::Deserializer<'de> for &'a mut Deserializer<R> {
///
/// # Examples
/// ```
/// # fn main() -> Result<(), serde_bencode::Error> {
/// # fn main() -> Result<(), torrust_serde_bencode::Error> {
/// use serde_derive::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
Expand All @@ -355,7 +355,7 @@ impl<'de, 'a, R: Read> de::Deserializer<'de> for &'a mut Deserializer<R> {
/// }
///
/// let encoded = "d4:city18:Duckburg, Calisota6:street17:1313 Webfoot Walke".to_string();
/// let decoded: Address = serde_bencode::from_str(&encoded)?;
/// let decoded: Address = torrust_serde_bencode::from_str(&encoded)?;
///
/// assert_eq!(
/// decoded,
Expand Down Expand Up @@ -384,7 +384,7 @@ where
///
/// # Examples
/// ```
/// # fn main() -> Result<(), serde_bencode::Error> {
/// # fn main() -> Result<(), torrust_serde_bencode::Error> {
/// use serde_derive::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
Expand All @@ -394,7 +394,7 @@ where
/// }
///
/// let encoded = "d4:city18:Duckburg, Calisota6:street17:1313 Webfoot Walke".as_bytes();
/// let decoded: Address = serde_bencode::from_bytes(&encoded)?;
/// let decoded: Address = torrust_serde_bencode::from_bytes(&encoded)?;
///
/// assert_eq!(
/// decoded,
Expand Down
18 changes: 9 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::fmt::Display;
use std::io::Error as IoError;
use std::result::Result as StdResult;

/// Alias for `Result<T, serde_bencode::Error>`.
/// Alias for `Result<T, torrust_serde_bencode::Error>`.
pub type Result<T> = StdResult<T, Error>;

/// Represents all possible errors which can occur when serializing or deserializing bencode.
Expand Down Expand Up @@ -107,14 +107,14 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match *self {
Error::IoError(ref error) => return error.fmt(f),
Error::InvalidType(ref s) => s,
Error::InvalidValue(ref s) => s,
Error::InvalidLength(ref s) => s,
Error::UnknownVariant(ref s) => s,
Error::UnknownField(ref s) => s,
Error::MissingField(ref s) => s,
Error::DuplicateField(ref s) => s,
Error::Custom(ref s) => s,
Error::InvalidType(ref s)
| Error::InvalidValue(ref s)
| Error::InvalidLength(ref s)
| Error::UnknownVariant(ref s)
| Error::UnknownField(ref s)
| Error::MissingField(ref s)
| Error::DuplicateField(ref s)
| Error::Custom(ref s) => s,
Error::EndOfStream => "End of stream",
};
f.write_str(message)
Expand Down
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
//! price: 130,
//! };
//!
//! let serialized = serde_bencode::to_string(&apple)?;
//!
//! let serialized = torrust_serde_bencode::to_string(&apple)?;
//!
//! // cspell:disable-next-line
//! assert_eq!(serialized, "d4:name5:Apple5:pricei130ee".to_string());
//!
//! let deserialized: Product = serde_bencode::from_str(&serialized)?;
//! let deserialized: Product = torrust_serde_bencode::from_str(&serialized)?;
//!
//! assert_eq!(
//! deserialized,
Expand Down
34 changes: 18 additions & 16 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ pub struct Serializer {

impl Serializer {
/// Create a new serializer.
#[must_use]
pub fn new() -> Serializer {
Self::default()
}

/// Consume the serializer and return the contents as a byte vector.
#[must_use]
pub fn into_vec(self) -> Vec<u8> {
self.buf
}
Expand Down Expand Up @@ -82,7 +84,7 @@ impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
}

#[doc(hidden)]
// TODO: This should be pub(crate).
// todo: This should be pub(crate).
pub struct SerializeMap<'a> {
ser: &'a mut Serializer,
entries: Vec<(Vec<u8>, Vec<u8>)>,
Expand All @@ -105,7 +107,7 @@ impl<'a> SerializeMap<'a> {
));
}
let mut entries = mem::take(&mut self.entries);
entries.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
entries.sort_by(|(a, _), (b, _)| a.cmp(b));
self.ser.push("d");
for (k, v) in entries {
ser::Serializer::serialize_bytes(&mut *self.ser, k.as_ref())?;
Expand All @@ -126,7 +128,7 @@ impl<'a> ser::SerializeMap for SerializeMap<'a> {
.to_string(),
));
}
self.cur_key = Some(key.serialize(&mut string::StringSerializer)?);
self.cur_key = Some(key.serialize(&mut string::Serializer)?);
Ok(())
}
fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
Expand Down Expand Up @@ -154,7 +156,7 @@ impl<'a> ser::SerializeMap for SerializeMap<'a> {
.to_string(),
));
}
let key = key.serialize(&mut string::StringSerializer)?;
let key = key.serialize(&mut string::Serializer)?;
let mut ser = Serializer::new();
value.serialize(&mut ser)?;
let value = ser.into_vec();
Expand Down Expand Up @@ -212,16 +214,16 @@ impl<'a> ser::Serializer for &'a mut Serializer {
type SerializeStructVariant = SerializeMap<'a>;

fn serialize_bool(self, value: bool) -> Result<()> {
self.serialize_i64(value as i64)
self.serialize_i64(i64::from(value))
}
fn serialize_i8(self, value: i8) -> Result<()> {
self.serialize_i64(value as i64)
self.serialize_i64(i64::from(value))
}
fn serialize_i16(self, value: i16) -> Result<()> {
self.serialize_i64(value as i64)
self.serialize_i64(i64::from(value))
}
fn serialize_i32(self, value: i32) -> Result<()> {
self.serialize_i64(value as i64)
self.serialize_i64(i64::from(value))
}
fn serialize_i64(self, value: i64) -> Result<()> {
self.push("i");
Expand All @@ -230,13 +232,13 @@ impl<'a> ser::Serializer for &'a mut Serializer {
Ok(())
}
fn serialize_u8(self, value: u8) -> Result<()> {
self.serialize_u64(value as u64)
self.serialize_u64(u64::from(value))
}
fn serialize_u16(self, value: u16) -> Result<()> {
self.serialize_u64(value as u64)
self.serialize_u64(u64::from(value))
}
fn serialize_u32(self, value: u32) -> Result<()> {
self.serialize_u64(value as u64)
self.serialize_u64(u64::from(value))
}
fn serialize_u64(self, value: u64) -> Result<()> {
self.push("i");
Expand Down Expand Up @@ -349,7 +351,7 @@ impl<'a> ser::Serializer for &'a mut Serializer {
///
/// # Examples
/// ```
/// # fn main() -> Result<(), serde_bencode::Error> {
/// # fn main() -> Result<(), torrust_serde_bencode::Error> {
/// use serde_derive::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
Expand All @@ -363,7 +365,7 @@ impl<'a> ser::Serializer for &'a mut Serializer {
/// city: "Duckburg, Calisota".to_string(),
/// };
///
/// let bytes = serde_bencode::to_bytes(&address)?;
/// let bytes = torrust_serde_bencode::to_bytes(&address)?;
/// assert_eq!(
/// String::from_utf8(bytes).unwrap(),
/// "d4:city18:Duckburg, Calisota6:street17:1313 Webfoot Walke",
Expand All @@ -386,7 +388,7 @@ pub fn to_bytes<T: ser::Serialize>(b: &T) -> Result<Vec<u8>> {
///
/// # Examples
/// ```
/// # fn main() -> Result<(), serde_bencode::Error> {
/// # fn main() -> Result<(), torrust_serde_bencode::Error> {
/// use serde_derive::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
Expand All @@ -401,7 +403,7 @@ pub fn to_bytes<T: ser::Serialize>(b: &T) -> Result<Vec<u8>> {
/// };
///
/// assert_eq!(
/// serde_bencode::to_string(&address)?,
/// torrust_serde_bencode::to_string(&address)?,
/// "d4:city18:Duckburg, Calisota6:street17:1313 Webfoot Walke".to_string(),
/// );
/// # Ok(())
Expand All @@ -416,6 +418,6 @@ pub fn to_string<T: ser::Serialize>(b: &T) -> Result<String> {
let mut ser = Serializer::new();
b.serialize(&mut ser)?;
str::from_utf8(ser.as_ref())
.map(|s| s.to_string())
.map(std::string::ToString::to_string)
.map_err(|_| Error::InvalidValue("Not an UTF-8".to_string()))
}
Loading

0 comments on commit b3b2a44

Please sign in to comment.