Skip to content

Commit

Permalink
Enforce code quality with clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
juntyr committed Sep 1, 2023
1 parent bf32db9 commit 833d840
Show file tree
Hide file tree
Showing 15 changed files with 247 additions and 191 deletions.
7 changes: 4 additions & 3 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ jobs:
profile: minimal
components: clippy
override: true
- uses: actions-rs/clippy-check@v1
with:
token: ${{ github.token }}
- run: cargo clippy -- -D warnings
- run: cargo clippy --features integer128 -- -D warnings
- run: cargo clippy --features indexmap -- -D warnings
- run: cargo clippy --all-features -- -D warnings

rustfmt:
name: "Format: stable"
Expand Down
35 changes: 26 additions & 9 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ impl<'de> Deserializer<'de> {
// Cannot implement trait here since output is tied to input lifetime 'de.
#[allow(clippy::should_implement_trait)]
pub fn from_str(input: &'de str) -> SpannedResult<Self> {
Self::from_str_with_options(input, Options::default())
Self::from_str_with_options(input, &Options::default())
}

pub fn from_bytes(input: &'de [u8]) -> SpannedResult<Self> {
Self::from_bytes_with_options(input, Options::default())
Self::from_bytes_with_options(input, &Options::default())
}

pub fn from_str_with_options(input: &'de str, options: Options) -> SpannedResult<Self> {
pub fn from_str_with_options(input: &'de str, options: &Options) -> SpannedResult<Self> {
let mut deserializer = Deserializer {
parser: Parser::new(input)?,
newtype_variant: false,
Expand All @@ -61,21 +61,34 @@ impl<'de> Deserializer<'de> {
Ok(deserializer)
}

pub fn from_bytes_with_options(input: &'de [u8], options: Options) -> SpannedResult<Self> {
Self::from_str_with_options(
str::from_utf8(input).map_err(|error| SpannedError::from_utf8_error(error, input))?,
options,
)
pub fn from_bytes_with_options(input: &'de [u8], options: &Options) -> SpannedResult<Self> {
let err = match str::from_utf8(input) {
Ok(input) => return Self::from_str_with_options(input, options),
Err(err) => err,
};

// FIXME: use [`utf8_chunks`](https://github.com/rust-lang/rust/issues/99543) once stabilised
#[allow(clippy::expect_used)]
let valid_input =
str::from_utf8(&input[..err.valid_up_to()]).expect("source is valid up to error");

Err(SpannedError {
code: err.into(),
position: Position::from_offset(valid_input, valid_input.len()),
})
}

#[must_use]
pub fn remainder(&self) -> &'de str {
self.parser.src()
}

#[must_use]
pub fn span_error(&self, code: Error) -> SpannedError {
self.parser.span_error(code)
}

#[must_use]
pub fn extensions(&self) -> Extensions {
self.parser.exts
}
Expand Down Expand Up @@ -661,7 +674,11 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.newtype_variant = false;

let mut canary_buffer = [0u8; SERDE_FLATTEN_CANARY.len()];
let _ = write!(canary_buffer.as_mut(), "{}", VisitorExpecting(&visitor));
std::mem::drop(write!(
canary_buffer.as_mut(),
"{}",
VisitorExpecting(&visitor)
));
let terminator = if canary_buffer == SERDE_FLATTEN_CANARY {
Terminator::MapAsStruct
} else {
Expand Down
55 changes: 34 additions & 21 deletions src/de/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ struct EmptyStruct1;
#[derive(Debug, PartialEq, Deserialize)]
struct EmptyStruct2 {}

#[derive(Debug, PartialEq, Deserialize)]
struct NewType(i32);

#[derive(Debug, PartialEq, Deserialize)]
struct TupleStruct(f32, f32);

#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
struct MyStruct {
x: f32,
Expand Down Expand Up @@ -48,15 +54,9 @@ fn test_struct() {
assert_eq!(Ok(my_struct), from_str("MyStruct(x:4,y:7,)"));
assert_eq!(Ok(my_struct), from_str("(x:4,y:7)"));

#[derive(Debug, PartialEq, Deserialize)]
struct NewType(i32);

assert_eq!(Ok(NewType(42)), from_str("NewType(42)"));
assert_eq!(Ok(NewType(33)), from_str("(33)"));

#[derive(Debug, PartialEq, Deserialize)]
struct TupleStruct(f32, f32);

assert_eq!(Ok(TupleStruct(2.0, 5.0)), from_str("TupleStruct(2,5,)"));
assert_eq!(Ok(TupleStruct(3.0, 4.0)), from_str("(3,4)"));
}
Expand Down Expand Up @@ -165,39 +165,52 @@ fn err<T>(kind: Error, line: usize, col: usize) -> SpannedResult<T> {
fn test_err_wrong_value() {
use std::collections::HashMap;

use self::Error::*;

assert_eq!(from_str::<f32>("'c'"), err(ExpectedFloat, 1, 1));
assert_eq!(from_str::<String>("'c'"), err(ExpectedString, 1, 1));
assert_eq!(from_str::<HashMap<u32, u32>>("'c'"), err(ExpectedMap, 1, 1));
assert_eq!(from_str::<[u8; 5]>("'c'"), err(ExpectedStructLike, 1, 1));
assert_eq!(from_str::<Vec<u32>>("'c'"), err(ExpectedArray, 1, 1));
assert_eq!(from_str::<MyEnum>("'c'"), err(ExpectedIdentifier, 1, 1));
assert_eq!(from_str::<f32>("'c'"), err(Error::ExpectedFloat, 1, 1));
assert_eq!(from_str::<String>("'c'"), err(Error::ExpectedString, 1, 1));
assert_eq!(
from_str::<HashMap<u32, u32>>("'c'"),
err(Error::ExpectedMap, 1, 1)
);
assert_eq!(
from_str::<[u8; 5]>("'c'"),
err(Error::ExpectedStructLike, 1, 1)
);
assert_eq!(from_str::<Vec<u32>>("'c'"), err(Error::ExpectedArray, 1, 1));
assert_eq!(
from_str::<MyEnum>("'c'"),
err(Error::ExpectedIdentifier, 1, 1)
);
assert_eq!(
from_str::<MyStruct>("'c'"),
err(ExpectedNamedStructLike("MyStruct"), 1, 1)
err(Error::ExpectedNamedStructLike("MyStruct"), 1, 1)
);
assert_eq!(
from_str::<MyStruct>("NotMyStruct(x: 4, y: 2)"),
err(
ExpectedDifferentStructName {
Error::ExpectedDifferentStructName {
expected: "MyStruct",
found: String::from("NotMyStruct")
},
1,
12
)
);
assert_eq!(from_str::<(u8, bool)>("'c'"), err(ExpectedStructLike, 1, 1));
assert_eq!(from_str::<bool>("notabool"), err(ExpectedBoolean, 1, 1));
assert_eq!(
from_str::<(u8, bool)>("'c'"),
err(Error::ExpectedStructLike, 1, 1)
);
assert_eq!(
from_str::<bool>("notabool"),
err(Error::ExpectedBoolean, 1, 1)
);

assert_eq!(
from_str::<MyStruct>("MyStruct(\n x: true)"),
err(ExpectedFloat, 2, 8)
err(Error::ExpectedFloat, 2, 8)
);
assert_eq!(
from_str::<MyStruct>("MyStruct(\n x: 3.5, \n y:)"),
err(ExpectedFloat, 3, 7)
err(Error::ExpectedFloat, 3, 7)
);
}

Expand Down Expand Up @@ -341,7 +354,7 @@ fn test_byte_stream() {
#[test]
fn test_numbers() {
assert_eq!(
Ok(vec![1234, 12345, 123456, 1234567, 555_555]),
Ok(vec![1234, 12345, 123_456, 1_234_567, 555_555]),
from_str("[1_234, 12_345, 1_2_3_4_5_6, 1_234_567, 5_55_55_5]"),
);
}
Expand Down
63 changes: 23 additions & 40 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ impl fmt::Display for SpannedError {
}

impl fmt::Display for Error {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Error::Fmt => f.write_str("Formatting RON failed"),
Error::Io(ref s) => f.write_str(s),
Error::Message(ref s) => f.write_str(s),
Error::Io(ref s) | Error::Message(ref s) => f.write_str(s),
#[allow(deprecated)]
Error::Base64Error(ref e) => fmt::Display::fmt(e, f),
Error::Eof => f.write_str("Unexpected end of RON"),
Expand All @@ -144,7 +144,7 @@ impl fmt::Display for Error {
Error::FloatUnderscore => f.write_str("Unexpected underscore in float"),
Error::ExpectedInteger => f.write_str("Expected integer"),
Error::ExpectedOption => f.write_str("Expected option"),
Error::ExpectedOptionEnd => f.write_str("Expected closing `)`"),
Error::ExpectedOptionEnd | Error::ExpectedStructLikeEnd => f.write_str("Expected closing `)`"),
Error::ExpectedMap => f.write_str("Expected opening `{`"),
Error::ExpectedMapColon => f.write_str("Expected colon"),
Error::ExpectedMapEnd => f.write_str("Expected closing `}`"),
Expand All @@ -165,7 +165,6 @@ impl fmt::Display for Error {
write!(f, "Expected opening `(` for struct {}", Identifier(name))
}
}
Error::ExpectedStructLikeEnd => f.write_str("Expected closing `)`"),
Error::ExpectedUnit => f.write_str("Expected unit"),
Error::ExpectedString => f.write_str("Expected string"),
Error::ExpectedByteString => f.write_str("Expected byte string"),
Expand Down Expand Up @@ -289,16 +288,12 @@ pub struct Position {
pub line: usize,
pub col: usize,
}

impl Position {
pub(crate) fn from_offset(src: &str, cursor: usize) -> Position {
let src = &src[..cursor];
let line = 1 + src.chars().filter(|&c| c == '\n').count();
let col = 1 + src
.rsplit('\n')
.next()
.expect("rsplit always yields at least one value")
.chars()
.count();
let col = 1 + src.chars().rev().take_while(|&c| c != '\n').count();
Position { line, col }
}
}
Expand Down Expand Up @@ -334,32 +329,30 @@ impl de::Error for Error {

impl<'a> fmt::Display for UnexpectedSerdeTypeValue<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use de::Unexpected::*;

match self.0 {
Bool(b) => write!(f, "the boolean `{}`", b),
Unsigned(i) => write!(f, "the unsigned integer `{}`", i),
Signed(i) => write!(f, "the signed integer `{}`", i),
Float(n) => write!(f, "the floating point number `{}`", n),
Char(c) => write!(f, "the UTF-8 character `{}`", c),
Str(s) => write!(f, "the string {:?}", s),
Bytes(b) => write!(f, "the byte string b\"{}\"", {
de::Unexpected::Bool(b) => write!(f, "the boolean `{}`", b),
de::Unexpected::Unsigned(i) => write!(f, "the unsigned integer `{}`", i),
de::Unexpected::Signed(i) => write!(f, "the signed integer `{}`", i),
de::Unexpected::Float(n) => write!(f, "the floating point number `{}`", n),
de::Unexpected::Char(c) => write!(f, "the UTF-8 character `{}`", c),
de::Unexpected::Str(s) => write!(f, "the string {:?}", s),
de::Unexpected::Bytes(b) => write!(f, "the byte string b\"{}\"", {
b.iter()
.flat_map(|c| std::ascii::escape_default(*c))
.map(char::from)
.collect::<String>()
}),
Unit => write!(f, "a unit value"),
Option => write!(f, "an optional value"),
NewtypeStruct => write!(f, "a newtype struct"),
Seq => write!(f, "a sequence"),
Map => write!(f, "a map"),
Enum => write!(f, "an enum"),
UnitVariant => write!(f, "a unit variant"),
NewtypeVariant => write!(f, "a newtype variant"),
TupleVariant => write!(f, "a tuple variant"),
StructVariant => write!(f, "a struct variant"),
Other(other) => f.write_str(other),
de::Unexpected::Unit => write!(f, "a unit value"),
de::Unexpected::Option => write!(f, "an optional value"),
de::Unexpected::NewtypeStruct => write!(f, "a newtype struct"),
de::Unexpected::Seq => write!(f, "a sequence"),
de::Unexpected::Map => write!(f, "a map"),
de::Unexpected::Enum => write!(f, "an enum"),
de::Unexpected::UnitVariant => write!(f, "a unit variant"),
de::Unexpected::NewtypeVariant => write!(f, "a newtype variant"),
de::Unexpected::TupleVariant => write!(f, "a tuple variant"),
de::Unexpected::StructVariant => write!(f, "a struct variant"),
de::Unexpected::Other(other) => f.write_str(other),
}
}
}
Expand Down Expand Up @@ -443,16 +436,6 @@ impl From<SpannedError> for Error {
}
}

impl SpannedError {
pub(crate) fn from_utf8_error(error: Utf8Error, src: &[u8]) -> Self {
let src = str::from_utf8(&src[..error.valid_up_to()]).expect("source is valid up to error");
Self {
code: error.into(),
position: Position::from_offset(src, error.valid_up_to()),
}
}
}

struct OneOf {
alts: &'static [&'static str],
none: &'static str,
Expand Down
1 change: 1 addition & 0 deletions src/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ bitflags::bitflags! {

impl Extensions {
/// Creates an extension flag from an ident.
#[must_use]
pub fn from_ident(ident: &str) -> Option<Extensions> {
match ident {
"unwrap_newtypes" => Some(Extensions::UNWRAP_NEWTYPES),
Expand Down
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
#![deny(clippy::correctness)]
#![deny(clippy::suspicious)]
#![deny(clippy::complexity)]
#![deny(clippy::perf)]
#![deny(clippy::style)]
#![warn(clippy::pedantic)]
#![cfg_attr(not(test), deny(clippy::unwrap_used))]
#![cfg_attr(not(test), deny(clippy::expect_used))]
#![deny(clippy::panic)]
#![warn(clippy::todo)]
#![deny(clippy::unimplemented)]
#![deny(clippy::unreachable)]
#![deny(unsafe_code)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![doc = include_str!("../README.md")]
#![doc(html_root_url = "https://docs.rs/ron/0.8.1")]

Expand Down
Loading

0 comments on commit 833d840

Please sign in to comment.