epee-encoding: enable workspace lints (#294)
Some checks are pending
Audit / audit (push) Waiting to run
CI / fmt (push) Waiting to run
CI / typo (push) Waiting to run
CI / ci (macos-latest, stable, bash) (push) Waiting to run
CI / ci (ubuntu-latest, stable, bash) (push) Waiting to run
CI / ci (windows-latest, stable-x86_64-pc-windows-gnu, msys2 {0}) (push) Waiting to run
Deny / audit (push) Waiting to run
Doc / build (push) Waiting to run
Doc / deploy (push) Blocked by required conditions

* epee-encoding: enable workspace lints

* fmt

* fixes

* fixes

* fmt
This commit is contained in:
hinto-janai 2024-09-20 10:13:55 -04:00 committed by GitHub
parent 5588671501
commit 57af45e01d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 96 additions and 72 deletions

View file

@ -25,3 +25,6 @@ thiserror = { workspace = true, optional = true}
[dev-dependencies] [dev-dependencies]
hex = { workspace = true, features = ["default"] } hex = { workspace = true, features = ["default"] }
[lints]
workspace = true

View file

@ -9,7 +9,7 @@ pub struct ContainerAsBlob<T: Containerable + EpeeValue>(Vec<T>);
impl<T: Containerable + EpeeValue> From<Vec<T>> for ContainerAsBlob<T> { impl<T: Containerable + EpeeValue> From<Vec<T>> for ContainerAsBlob<T> {
fn from(value: Vec<T>) -> Self { fn from(value: Vec<T>) -> Self {
ContainerAsBlob(value) Self(value)
} }
} }
@ -36,9 +36,7 @@ impl<T: Containerable + EpeeValue> EpeeValue for ContainerAsBlob<T> {
)); ));
} }
Ok(ContainerAsBlob( Ok(Self(bytes.chunks(T::SIZE).map(T::from_bytes).collect()))
bytes.chunks(T::SIZE).map(T::from_bytes).collect(),
))
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -46,10 +44,10 @@ impl<T: Containerable + EpeeValue> EpeeValue for ContainerAsBlob<T> {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(ContainerAsBlob(vec![])) Some(Self(vec![]))
} }
fn write<B: BufMut>(self, w: &mut B) -> crate::Result<()> { fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
let mut buf = BytesMut::with_capacity(self.0.len() * T::SIZE); let mut buf = BytesMut::with_capacity(self.0.len() * T::SIZE);
self.0.iter().for_each(|tt| tt.push_bytes(&mut buf)); self.0.iter().for_each(|tt| tt.push_bytes(&mut buf));
buf.write(w) buf.write(w)

View file

@ -7,6 +7,7 @@ use core::{
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
#[cfg_attr(feature = "std", derive(thiserror::Error))] #[cfg_attr(feature = "std", derive(thiserror::Error))]
#[expect(clippy::error_impl_error, reason = "FIXME: rename this type")]
pub enum Error { pub enum Error {
#[cfg_attr(feature = "std", error("IO error: {0}"))] #[cfg_attr(feature = "std", error("IO error: {0}"))]
IO(&'static str), IO(&'static str),
@ -17,19 +18,18 @@ pub enum Error {
} }
impl Error { impl Error {
fn field_name(&self) -> &'static str { const fn field_name(&self) -> &'static str {
match self { match self {
Error::IO(_) => "io", Self::IO(_) => "io",
Error::Format(_) => "format", Self::Format(_) => "format",
Error::Value(_) => "value", Self::Value(_) => "value",
} }
} }
fn field_data(&self) -> &str { fn field_data(&self) -> &str {
match self { match self {
Error::IO(data) => data, Self::IO(data) | Self::Format(data) => data,
Error::Format(data) => data, Self::Value(data) => data,
Error::Value(data) => data,
} }
} }
} }
@ -44,12 +44,12 @@ impl Debug for Error {
impl From<TryFromIntError> for Error { impl From<TryFromIntError> for Error {
fn from(_: TryFromIntError) -> Self { fn from(_: TryFromIntError) -> Self {
Error::Value("Int is too large".to_string()) Self::Value("Int is too large".to_string())
} }
} }
impl From<Utf8Error> for Error { impl From<Utf8Error> for Error {
fn from(_: Utf8Error) -> Self { fn from(_: Utf8Error) -> Self {
Error::Value("Invalid utf8 str".to_string()) Self::Value("Invalid utf8 str".to_string())
} }
} }

View file

@ -3,7 +3,7 @@ use bytes::{Buf, BufMut};
use crate::error::*; use crate::error::*;
#[inline] #[inline]
pub fn checked_read_primitive<B: Buf, R: Sized>( pub(crate) fn checked_read_primitive<B: Buf, R: Sized>(
b: &mut B, b: &mut B,
read: impl Fn(&mut B) -> R, read: impl Fn(&mut B) -> R,
) -> Result<R> { ) -> Result<R> {
@ -11,16 +11,20 @@ pub fn checked_read_primitive<B: Buf, R: Sized>(
} }
#[inline] #[inline]
pub fn checked_read<B: Buf, R>(b: &mut B, read: impl Fn(&mut B) -> R, size: usize) -> Result<R> { pub(crate) fn checked_read<B: Buf, R>(
b: &mut B,
read: impl Fn(&mut B) -> R,
size: usize,
) -> Result<R> {
if b.remaining() < size { if b.remaining() < size {
Err(Error::IO("Not enough bytes in buffer to build object."))?; Err(Error::IO("Not enough bytes in buffer to build object."))
} } else {
Ok(read(b)) Ok(read(b))
}
} }
#[inline] #[inline]
pub fn checked_write_primitive<B: BufMut, T: Sized>( pub(crate) fn checked_write_primitive<B: BufMut, T: Sized>(
b: &mut B, b: &mut B,
write: impl Fn(&mut B, T), write: impl Fn(&mut B, T),
t: T, t: T,
@ -29,16 +33,16 @@ pub fn checked_write_primitive<B: BufMut, T: Sized>(
} }
#[inline] #[inline]
pub fn checked_write<B: BufMut, T>( pub(crate) fn checked_write<B: BufMut, T>(
b: &mut B, b: &mut B,
write: impl Fn(&mut B, T), write: impl Fn(&mut B, T),
t: T, t: T,
size: usize, size: usize,
) -> Result<()> { ) -> Result<()> {
if b.remaining_mut() < size { if b.remaining_mut() < size {
Err(Error::IO("Not enough capacity to write object."))?; Err(Error::IO("Not enough capacity to write object."))
} } else {
write(b, t); write(b, t);
Ok(()) Ok(())
}
} }

View file

@ -59,9 +59,12 @@
//! //!
//! ``` //! ```
#[cfg(test)]
use hex as _;
extern crate alloc; extern crate alloc;
use core::{ops::Deref, str::from_utf8 as str_from_utf8}; use core::str::from_utf8 as str_from_utf8;
use bytes::{Buf, BufMut, Bytes, BytesMut}; use bytes::{Buf, BufMut, Bytes, BytesMut};
@ -130,7 +133,7 @@ pub fn to_bytes<T: EpeeObject>(val: T) -> Result<BytesMut> {
fn read_header<B: Buf>(r: &mut B) -> Result<()> { fn read_header<B: Buf>(r: &mut B) -> Result<()> {
let buf = checked_read(r, |b: &mut B| b.copy_to_bytes(HEADER.len()), HEADER.len())?; let buf = checked_read(r, |b: &mut B| b.copy_to_bytes(HEADER.len()), HEADER.len())?;
if buf.deref() != HEADER { if &*buf != HEADER {
return Err(Error::Format("Data does not contain header")); return Err(Error::Format("Data does not contain header"));
} }
Ok(()) Ok(())
@ -185,7 +188,7 @@ fn read_object<T: EpeeObject, B: Buf>(r: &mut B, skipped_objects: &mut u8) -> Re
for _ in 0..number_o_field { for _ in 0..number_o_field {
let field_name_bytes = read_field_name_bytes(r)?; let field_name_bytes = read_field_name_bytes(r)?;
let field_name = str_from_utf8(field_name_bytes.deref())?; let field_name = str_from_utf8(&field_name_bytes)?;
if !object_builder.add_field(field_name, r)? { if !object_builder.add_field(field_name, r)? {
skip_epee_value(r, skipped_objects)?; skip_epee_value(r, skipped_objects)?;
@ -289,7 +292,7 @@ where
B: BufMut, B: BufMut,
{ {
write_varint(usize_to_u64(iterator.len()), w)?; write_varint(usize_to_u64(iterator.len()), w)?;
for item in iterator.into_iter() { for item in iterator {
item.write(w)?; item.write(w)?;
} }
Ok(()) Ok(())
@ -329,10 +332,7 @@ impl EpeeObject for SkipObject {
fn skip_epee_value<B: Buf>(r: &mut B, skipped_objects: &mut u8) -> Result<()> { fn skip_epee_value<B: Buf>(r: &mut B, skipped_objects: &mut u8) -> Result<()> {
let marker = read_marker(r)?; let marker = read_marker(r)?;
let mut len = 1; let len = if marker.is_seq { read_varint(r)? } else { 1 };
if marker.is_seq {
len = read_varint(r)?;
}
if let Some(size) = marker.inner_marker.size() { if let Some(size) = marker.inner_marker.size() {
let bytes_to_skip = size let bytes_to_skip = size

View file

@ -19,13 +19,13 @@ pub enum InnerMarker {
} }
impl InnerMarker { impl InnerMarker {
pub fn size(&self) -> Option<usize> { pub const fn size(&self) -> Option<usize> {
Some(match self { Some(match self {
InnerMarker::I64 | InnerMarker::U64 | InnerMarker::F64 => 8, Self::I64 | Self::U64 | Self::F64 => 8,
InnerMarker::I32 | InnerMarker::U32 => 4, Self::I32 | Self::U32 => 4,
InnerMarker::I16 | InnerMarker::U16 => 2, Self::I16 | Self::U16 => 2,
InnerMarker::I8 | InnerMarker::U8 | InnerMarker::Bool => 1, Self::I8 | Self::U8 | Self::Bool => 1,
InnerMarker::String | InnerMarker::Object => return None, Self::String | Self::Object => return None,
}) })
} }
} }
@ -40,23 +40,23 @@ pub struct Marker {
impl Marker { impl Marker {
pub(crate) const fn new(inner_marker: InnerMarker) -> Self { pub(crate) const fn new(inner_marker: InnerMarker) -> Self {
Marker { Self {
inner_marker, inner_marker,
is_seq: false, is_seq: false,
} }
} }
#[must_use]
pub const fn into_seq(self) -> Self { pub const fn into_seq(self) -> Self {
if self.is_seq { assert!(!self.is_seq, "Sequence of sequence not allowed!");
panic!("Sequence of sequence not allowed!");
}
if matches!(self.inner_marker, InnerMarker::U8) { if matches!(self.inner_marker, InnerMarker::U8) {
return Marker { return Self {
inner_marker: InnerMarker::String, inner_marker: InnerMarker::String,
is_seq: false, is_seq: false,
}; };
} }
Marker { Self {
inner_marker: self.inner_marker, inner_marker: self.inner_marker,
is_seq: true, is_seq: true,
} }
@ -112,7 +112,7 @@ impl TryFrom<u8> for Marker {
_ => return Err(Error::Format("Unknown value Marker")), _ => return Err(Error::Format("Unknown value Marker")),
}; };
Ok(Marker { Ok(Self {
inner_marker, inner_marker,
is_seq, is_seq,
}) })

View file

@ -71,7 +71,7 @@ impl<T: EpeeObject> EpeeValue for Vec<T> {
let individual_marker = Marker::new(marker.inner_marker); let individual_marker = Marker::new(marker.inner_marker);
let mut res = Vec::with_capacity(len); let mut res = Self::with_capacity(len);
for _ in 0..len { for _ in 0..len {
res.push(T::read(r, &individual_marker)?); res.push(T::read(r, &individual_marker)?);
} }
@ -83,7 +83,7 @@ impl<T: EpeeObject> EpeeValue for Vec<T> {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(Vec::new()) Some(Self::new())
} }
fn write<B: BufMut>(self, w: &mut B) -> Result<()> { fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
@ -181,7 +181,7 @@ impl EpeeValue for Vec<u8> {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(Vec::new()) Some(Self::new())
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -216,7 +216,7 @@ impl EpeeValue for Bytes {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(Bytes::new()) Some(Self::new())
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -247,14 +247,14 @@ impl EpeeValue for BytesMut {
return Err(Error::IO("Not enough bytes to fill object")); return Err(Error::IO("Not enough bytes to fill object"));
} }
let mut bytes = BytesMut::zeroed(len); let mut bytes = Self::zeroed(len);
r.copy_to_slice(&mut bytes); r.copy_to_slice(&mut bytes);
Ok(bytes) Ok(bytes)
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(BytesMut::new()) Some(Self::new())
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -285,12 +285,11 @@ impl<const N: usize> EpeeValue for ByteArrayVec<N> {
return Err(Error::IO("Not enough bytes to fill object")); return Err(Error::IO("Not enough bytes to fill object"));
} }
ByteArrayVec::try_from(r.copy_to_bytes(len)) Self::try_from(r.copy_to_bytes(len)).map_err(|_| Error::Format("Field has invalid length"))
.map_err(|_| Error::Format("Field has invalid length"))
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(ByteArrayVec::try_from(Bytes::new()).unwrap()) Some(Self::try_from(Bytes::new()).unwrap())
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -320,8 +319,7 @@ impl<const N: usize> EpeeValue for ByteArray<N> {
return Err(Error::IO("Not enough bytes to fill object")); return Err(Error::IO("Not enough bytes to fill object"));
} }
ByteArray::try_from(r.copy_to_bytes(N)) Self::try_from(r.copy_to_bytes(N)).map_err(|_| Error::Format("Field has invalid length"))
.map_err(|_| Error::Format("Field has invalid length"))
} }
fn write<B: BufMut>(self, w: &mut B) -> Result<()> { fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
@ -335,7 +333,7 @@ impl EpeeValue for String {
fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> { fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
let bytes = Vec::<u8>::read(r, marker)?; let bytes = Vec::<u8>::read(r, marker)?;
String::from_utf8(bytes).map_err(|_| Error::Format("Invalid string")) Self::from_utf8(bytes).map_err(|_| Error::Format("Invalid string"))
} }
fn should_write(&self) -> bool { fn should_write(&self) -> bool {
@ -343,7 +341,7 @@ impl EpeeValue for String {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(String::new()) Some(Self::new())
} }
fn write<B: BufMut>(self, w: &mut B) -> Result<()> { fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
@ -383,7 +381,7 @@ impl<const N: usize> EpeeValue for Vec<[u8; N]> {
let individual_marker = Marker::new(marker.inner_marker); let individual_marker = Marker::new(marker.inner_marker);
let mut res = Vec::with_capacity(len); let mut res = Self::with_capacity(len);
for _ in 0..len { for _ in 0..len {
res.push(<[u8; N]>::read(r, &individual_marker)?); res.push(<[u8; N]>::read(r, &individual_marker)?);
} }
@ -395,7 +393,7 @@ impl<const N: usize> EpeeValue for Vec<[u8; N]> {
} }
fn epee_default_value() -> Option<Self> { fn epee_default_value() -> Option<Self> {
Some(Vec::new()) Some(Self::new())
} }
fn write<B: BufMut>(self, w: &mut B) -> Result<()> { fn write<B: BufMut>(self, w: &mut B) -> Result<()> {

View file

@ -21,14 +21,14 @@ const FITS_IN_FOUR_BYTES: u64 = 2_u64.pow(32 - SIZE_OF_SIZE_MARKER) - 1;
/// ``` /// ```
pub fn read_varint<B: Buf>(r: &mut B) -> Result<u64> { pub fn read_varint<B: Buf>(r: &mut B) -> Result<u64> {
if !r.has_remaining() { if !r.has_remaining() {
Err(Error::IO("Not enough bytes to build VarInt"))? return Err(Error::IO("Not enough bytes to build VarInt"));
} }
let vi_start = r.get_u8(); let vi_start = r.get_u8();
let len = 1 << (vi_start & 0b11); let len = 1 << (vi_start & 0b11);
if r.remaining() < len - 1 { if r.remaining() < len - 1 {
Err(Error::IO("Not enough bytes to build VarInt"))? return Err(Error::IO("Not enough bytes to build VarInt"));
} }
let mut vi = u64::from(vi_start >> 2); let mut vi = u64::from(vi_start >> 2);
@ -67,12 +67,15 @@ pub fn write_varint<B: BufMut>(number: u64, w: &mut B) -> Result<()> {
}; };
if w.remaining_mut() < 1 << size_marker { if w.remaining_mut() < 1 << size_marker {
Err(Error::IO("Not enough capacity to write VarInt"))?; return Err(Error::IO("Not enough capacity to write VarInt"));
} }
let number = (number << 2) | size_marker; let number = (number << 2) | size_marker;
// Although `as` is unsafe we just checked the length. #[expect(
clippy::cast_possible_truncation,
reason = "Although `as` is unsafe we just checked the length."
)]
match size_marker { match size_marker {
0 => w.put_u8(number as u8), 0 => w.put_u8(number as u8),
1 => w.put_u16_le(number as u16), 1 => w.put_u16_le(number as u16),

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
struct AltName { struct AltName {

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes};
struct T { struct T {

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
pub struct Optional { pub struct Optional {
@ -58,7 +60,7 @@ fn epee_non_default_does_encode() {
let val: Optional = from_bytes(&mut bytes).unwrap(); let val: Optional = from_bytes(&mut bytes).unwrap();
assert_eq!(val.optional_val, -3); assert_eq!(val.optional_val, -3);
assert_eq!(val.val, 8) assert_eq!(val.val, 8);
} }
#[test] #[test]
@ -70,5 +72,5 @@ fn epee_value_not_present_with_default() {
let val: Optional = from_bytes(&mut bytes).unwrap(); let val: Optional = from_bytes(&mut bytes).unwrap();
assert_eq!(val.optional_val, -4); assert_eq!(val.optional_val, -4);
assert_eq!(val.val, 76) assert_eq!(val.val, 76);
} }

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
struct Child { struct Child {
@ -37,6 +39,7 @@ epee_object!(
); );
#[test] #[test]
#[expect(clippy::float_cmp)]
fn epee_flatten() { fn epee_flatten() {
let val2 = ParentChild { let val2 = ParentChild {
h: 38.9, h: 38.9,

View file

@ -1,5 +1,6 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
use std::ops::Deref;
#[derive(Clone)] #[derive(Clone)]
struct T { struct T {
@ -28,6 +29,6 @@ fn optional_val_in_data() {
]; ];
let t: T = from_bytes(&mut &bytes[..]).unwrap(); let t: T = from_bytes(&mut &bytes[..]).unwrap();
let bytes2 = to_bytes(t.clone()).unwrap(); let bytes2 = to_bytes(t.clone()).unwrap();
assert_eq!(bytes.as_slice(), bytes2.deref()); assert_eq!(bytes.as_slice(), &*bytes2);
assert_eq!(t.val.unwrap(), 21); assert_eq!(t.val.unwrap(), 21);
} }

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
#[derive(Eq, PartialEq, Debug, Clone)] #[derive(Eq, PartialEq, Debug, Clone)]
@ -5,7 +7,7 @@ pub struct SupportFlags(u32);
impl From<u32> for SupportFlags { impl From<u32> for SupportFlags {
fn from(value: u32) -> Self { fn from(value: u32) -> Self {
SupportFlags(value) Self(value)
} }
} }

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes, to_bytes};
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes};
struct ObjSeq { struct ObjSeq {

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes}; use cuprate_epee_encoding::{epee_object, from_bytes};
struct D { struct D {
@ -737,5 +739,5 @@ fn stack_overflow() {
let obj: Result<Q, _> = from_bytes(&mut bytes.as_slice()); let obj: Result<Q, _> = from_bytes(&mut bytes.as_slice());
assert!(obj.is_err()) assert!(obj.is_err());
} }