Skip to content

Commit

Permalink
Fix warnings and clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
madadam authored and toby committed Oct 25, 2021
1 parent e6f9b53 commit 1eecff4
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 52 deletions.
31 changes: 14 additions & 17 deletions examples/parse_torrent.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
extern crate serde_bencode;
extern crate serde;
extern crate serde_bencode;
#[macro_use]
extern crate serde_derive;
extern crate serde_bytes;

use serde_bencode::de;
use std::io::{self, Read};
use serde_bytes::ByteBuf;
use std::io::{self, Read};

#[derive(Debug, Deserialize)]
struct Node(String, i64);
Expand All @@ -23,7 +23,7 @@ struct File {
struct Info {
name: String,
pieces: ByteBuf,
#[serde(rename="piece length")]
#[serde(rename = "piece length")]
piece_length: i64,
#[serde(default)]
md5sum: Option<String>,
Expand All @@ -36,7 +36,7 @@ struct Info {
#[serde(default)]
path: Option<Vec<String>>,
#[serde(default)]
#[serde(rename="root hash")]
#[serde(rename = "root hash")]
root_hash: Option<String>,
}

Expand All @@ -52,23 +52,23 @@ struct Torrent {
#[serde(default)]
httpseeds: Option<Vec<String>>,
#[serde(default)]
#[serde(rename="announce-list")]
#[serde(rename = "announce-list")]
announce_list: Option<Vec<Vec<String>>>,
#[serde(default)]
#[serde(rename="creation date")]
#[serde(rename = "creation date")]
creation_date: Option<i64>,
#[serde(rename="comment")]
#[serde(rename = "comment")]
comment: Option<String>,
#[serde(default)]
#[serde(rename="created by")]
#[serde(rename = "created by")]
created_by: Option<String>,
}

fn render_torrent(torrent: &Torrent) {
println!("name:\t\t{}", torrent.info.name);
println!("announce:\t{:?}", torrent.announce);
println!("nodes:\t\t{:?}", torrent.nodes);
if let &Some(ref al) = &torrent.announce_list {
if let Some(al) = &torrent.announce_list {
for a in al {
println!("announce list:\t{}", a[0]);
}
Expand All @@ -83,7 +83,7 @@ fn render_torrent(torrent: &Torrent) {
println!("root hash:\t{:?}", torrent.info.root_hash);
println!("md5sum:\t\t{:?}", torrent.info.md5sum);
println!("path:\t\t{:?}", torrent.info.path);
if let &Some(ref files) = &torrent.info.files {
if let Some(files) = &torrent.info.files {
for f in files {
println!("file path:\t{:?}", f.path);
println!("file length:\t{}", f.length);
Expand All @@ -97,13 +97,10 @@ fn main() {
let mut buffer = Vec::new();
let mut handle = stdin.lock();
match handle.read_to_end(&mut buffer) {
Ok(_) => {
match de::from_bytes::<Torrent>(&buffer) {
Ok(t) => render_torrent(&t),
Err(e) => println!("ERROR: {:?}", e),
}
}
Ok(_) => match de::from_bytes::<Torrent>(&buffer) {
Ok(t) => render_torrent(&t),
Err(e) => println!("ERROR: {:?}", e),
},
Err(e) => println!("ERROR: {:?}", e),

}
}
28 changes: 11 additions & 17 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct BencodeAccess<'a, R: 'a + Read> {

impl<'a, R: 'a + Read> BencodeAccess<'a, R> {
fn new(de: &'a mut Deserializer<R>, len: Option<usize>) -> BencodeAccess<'a, R> {
BencodeAccess { de: de, len: len }
BencodeAccess { de, len }
}
}

Expand All @@ -27,20 +27,17 @@ impl<'de, 'a, R: 'a + Read> de::SeqAccess<'de> for BencodeAccess<'a, R> {
) -> Result<Option<T::Value>> {
let res = match self.de.parse()? {
ParseResult::End => Ok(None),
r @ _ => {
r => {
self.de.next = Some(r);
Ok(Some(seed.deserialize(&mut *self.de)?))
}
};
match self.len {
Some(l) => {
let l = l - 1;
self.len = Some(l);
if l == 0 && ParseResult::End != self.de.parse()? {
return Err(Error::InvalidType("expected `e`".to_string()));
}
if let Some(l) = self.len {
let l = l - 1;
self.len = Some(l);
if l == 0 && ParseResult::End != self.de.parse()? {
return Err(Error::InvalidType("expected `e`".to_string()));
}
None => (),
}
res
}
Expand All @@ -54,7 +51,7 @@ impl<'de, 'a, R: 'a + Read> de::MapAccess<'de> for BencodeAccess<'a, R> {
{
match self.de.parse()? {
ParseResult::End => Ok(None),
r @ _ => {
r => {
self.de.next = Some(r);
Ok(Some(seed.deserialize(&mut *self.de)?))
}
Expand Down Expand Up @@ -118,7 +115,7 @@ impl<'de, 'a, R: 'a + Read> de::EnumAccess<'de> for BencodeAccess<'a, R> {
Ok((seed.deserialize(&mut *self.de)?, self))
}
ParseResult::Map => Ok((seed.deserialize(&mut *self.de)?, self)),
t @ _ => Err(Error::InvalidValue(format!(
t => Err(Error::InvalidValue(format!(
"Expected bytes or map; got `{:?}`",
t
))),
Expand Down Expand Up @@ -148,10 +145,7 @@ pub struct Deserializer<R: Read> {
impl<'de, R: Read> Deserializer<R> {
/// Create a new deserializer.
pub fn new(reader: R) -> Deserializer<R> {
Deserializer {
reader: reader,
next: None,
}
Deserializer { reader, next: None }
}

fn parse_int(&mut self) -> Result<i64> {
Expand Down Expand Up @@ -226,7 +220,7 @@ impl<'de, R: Read> Deserializer<R> {
b'l' => Ok(ParseResult::List),
b'd' => Ok(ParseResult::Map),
b'e' => Ok(ParseResult::End),
c @ _ => Err(Error::InvalidValue(format!(
c => Err(Error::InvalidValue(format!(
"Invalid character `{}`",
c as char
))),
Expand Down
16 changes: 9 additions & 7 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ use std::mem;
use std::str;

/// A structure for serializing Rust values into bencode.
#[derive(Debug)]
#[derive(Default, Debug)]
pub struct Serializer {
buf: Vec<u8>,
}

impl Serializer {
/// Create a new serializer.
pub fn new() -> Serializer {
Serializer { buf: Vec::new() }
Self::default()
}

/// Consume the serializer and return the contents as a byte vector.
Expand Down Expand Up @@ -92,7 +92,7 @@ pub struct SerializeMap<'a> {
impl<'a> SerializeMap<'a> {
pub fn new(ser: &'a mut Serializer, len: usize) -> SerializeMap {
SerializeMap {
ser: ser,
ser,
entries: Vec::with_capacity(len),
cur_key: None,
}
Expand All @@ -104,7 +104,7 @@ impl<'a> SerializeMap<'a> {
"`serialize_key` called without calling `serialize_value`".to_string(),
));
}
let mut entries = mem::replace(&mut self.entries, Vec::new());
let mut entries = mem::take(&mut self.entries);
entries.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
self.ser.push("d");
for (k, v) in entries {
Expand All @@ -130,9 +130,11 @@ impl<'a> ser::SerializeMap for SerializeMap<'a> {
Ok(())
}
fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
let key = self.cur_key.take().ok_or(Error::InvalidValue(
"`serialize_value` called without calling `serialize_key`".to_string(),
))?;
let key = self.cur_key.take().ok_or_else(|| {
Error::InvalidValue(
"`serialize_value` called without calling `serialize_key`".to_string(),
)
})?;
let mut ser = Serializer::new();
value.serialize(&mut ser)?;
let value = ser.into_vec();
Expand Down
22 changes: 11 additions & 11 deletions tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extern crate serde_bencode;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde::Serialize;
use serde_bencode::de::{from_bytes, from_str};
use serde_bencode::error::Result;
use serde_bencode::ser::{to_bytes, to_string, Serializer};
Expand Down Expand Up @@ -178,7 +178,7 @@ fn serialize_struct() {
struct Fake {
x: i64,
y: String,
};
}
let f = Fake {
x: 1111,
y: "dog".to_string(),
Expand All @@ -193,7 +193,7 @@ fn deserialize_to_struct() {
struct Fake {
y: String,
x: i64,
};
}
assert_eq!(
from_str::<Fake>(b).unwrap(),
Fake {
Expand All @@ -214,7 +214,7 @@ fn deserialize_to_struct_with_option() {
z: Option<String>,
#[serde(default)]
a: Option<String>,
};
}
let r: Fake = from_str(b).unwrap();
assert_eq!(
r,
Expand Down Expand Up @@ -246,7 +246,7 @@ fn deserialize_to_value_struct_mix() {
x: i64,
z: Value,
q: Vec<i64>,
};
}
let r: Fake = from_str(b).unwrap();
assert_eq!(
r,
Expand All @@ -267,7 +267,7 @@ fn serialize_lexical_sorted_keys() {
bb: i32,
z: i32,
c: i32,
};
}
let f = Fake {
aaa: 1,
bb: 2,
Expand Down Expand Up @@ -324,7 +324,7 @@ fn struct_none_vals() {
struct Fake {
a: Option<i32>,
b: Option<i32>,
};
}
let f = Fake {
a: None,
b: Some(1),
Expand All @@ -338,7 +338,7 @@ fn ser_de_variant_unit() {
enum Mock {
A,
B,
};
}
test_ser_de_eq(("pre".to_string(), Mock::A, "post".to_string()));
test_ser_de_eq(("pre".to_string(), Mock::B, "post".to_string()));
}
Expand All @@ -349,7 +349,7 @@ fn ser_de_variant_newtype() {
enum Mock {
A(i64),
B(i64),
};
}
test_ser_de_eq(("pre".to_string(), Mock::A(123), "post".to_string()));
test_ser_de_eq(("pre".to_string(), Mock::B(321), "post".to_string()));
}
Expand All @@ -360,7 +360,7 @@ fn ser_de_variant_tuple() {
enum Mock {
A(i64, i64),
B(i64, i64),
};
}
test_ser_de_eq(("pre".to_string(), Mock::A(123, 321), "post".to_string()));
test_ser_de_eq(("pre".to_string(), Mock::B(321, 123), "post".to_string()));
}
Expand All @@ -371,7 +371,7 @@ fn ser_de_variant_struct() {
enum Mock {
A { a: i64, b: i64 },
B { c: i64, d: i64 },
};
}
test_ser_de_eq((
"pre".to_string(),
Mock::A { a: 123, b: 321 },
Expand Down

0 comments on commit 1eecff4

Please sign in to comment.