epee-encoding: enable workspace lints (#294)

* 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]
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> {
fn from(value: Vec<T>) -> Self {
ContainerAsBlob(value)
Self(value)
}
}
@ -36,9 +36,7 @@ impl<T: Containerable + EpeeValue> EpeeValue for ContainerAsBlob<T> {
));
}
Ok(ContainerAsBlob(
bytes.chunks(T::SIZE).map(T::from_bytes).collect(),
))
Ok(Self(bytes.chunks(T::SIZE).map(T::from_bytes).collect()))
}
fn should_write(&self) -> bool {
@ -46,10 +44,10 @@ impl<T: Containerable + EpeeValue> EpeeValue for ContainerAsBlob<T> {
}
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);
self.0.iter().for_each(|tt| tt.push_bytes(&mut buf));
buf.write(w)

View file

@ -7,6 +7,7 @@ use core::{
pub type Result<T> = core::result::Result<T, Error>;
#[cfg_attr(feature = "std", derive(thiserror::Error))]
#[expect(clippy::error_impl_error, reason = "FIXME: rename this type")]
pub enum Error {
#[cfg_attr(feature = "std", error("IO error: {0}"))]
IO(&'static str),
@ -17,19 +18,18 @@ pub enum Error {
}
impl Error {
fn field_name(&self) -> &'static str {
const fn field_name(&self) -> &'static str {
match self {
Error::IO(_) => "io",
Error::Format(_) => "format",
Error::Value(_) => "value",
Self::IO(_) => "io",
Self::Format(_) => "format",
Self::Value(_) => "value",
}
}
fn field_data(&self) -> &str {
match self {
Error::IO(data) => data,
Error::Format(data) => data,
Error::Value(data) => data,
Self::IO(data) | Self::Format(data) => data,
Self::Value(data) => data,
}
}
}
@ -44,12 +44,12 @@ impl Debug for Error {
impl From<TryFromIntError> for Error {
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 {
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::*;
#[inline]
pub fn checked_read_primitive<B: Buf, R: Sized>(
pub(crate) fn checked_read_primitive<B: Buf, R: Sized>(
b: &mut B,
read: impl Fn(&mut B) -> R,
) -> Result<R> {
@ -11,16 +11,20 @@ pub fn checked_read_primitive<B: Buf, R: Sized>(
}
#[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 {
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]
pub fn checked_write_primitive<B: BufMut, T: Sized>(
pub(crate) fn checked_write_primitive<B: BufMut, T: Sized>(
b: &mut B,
write: impl Fn(&mut B, T),
t: T,
@ -29,16 +33,16 @@ pub fn checked_write_primitive<B: BufMut, T: Sized>(
}
#[inline]
pub fn checked_write<B: BufMut, T>(
pub(crate) fn checked_write<B: BufMut, T>(
b: &mut B,
write: impl Fn(&mut B, T),
t: T,
size: usize,
) -> Result<()> {
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);
Ok(())
}
write(b, t);
Ok(())
}

View file

@ -59,9 +59,12 @@
//!
//! ```
#[cfg(test)]
use hex as _;
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};
@ -130,7 +133,7 @@ pub fn to_bytes<T: EpeeObject>(val: T) -> Result<BytesMut> {
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())?;
if buf.deref() != HEADER {
if &*buf != HEADER {
return Err(Error::Format("Data does not contain header"));
}
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 {
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)? {
skip_epee_value(r, skipped_objects)?;
@ -289,7 +292,7 @@ where
B: BufMut,
{
write_varint(usize_to_u64(iterator.len()), w)?;
for item in iterator.into_iter() {
for item in iterator {
item.write(w)?;
}
Ok(())
@ -329,10 +332,7 @@ impl EpeeObject for SkipObject {
fn skip_epee_value<B: Buf>(r: &mut B, skipped_objects: &mut u8) -> Result<()> {
let marker = read_marker(r)?;
let mut len = 1;
if marker.is_seq {
len = read_varint(r)?;
}
let len = if marker.is_seq { read_varint(r)? } else { 1 };
if let Some(size) = marker.inner_marker.size() {
let bytes_to_skip = size

View file

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

View file

@ -71,7 +71,7 @@ impl<T: EpeeObject> EpeeValue for Vec<T> {
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 {
res.push(T::read(r, &individual_marker)?);
}
@ -83,7 +83,7 @@ impl<T: EpeeObject> EpeeValue for Vec<T> {
}
fn epee_default_value() -> Option<Self> {
Some(Vec::new())
Some(Self::new())
}
fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
@ -181,7 +181,7 @@ impl EpeeValue for Vec<u8> {
}
fn epee_default_value() -> Option<Self> {
Some(Vec::new())
Some(Self::new())
}
fn should_write(&self) -> bool {
@ -216,7 +216,7 @@ impl EpeeValue for Bytes {
}
fn epee_default_value() -> Option<Self> {
Some(Bytes::new())
Some(Self::new())
}
fn should_write(&self) -> bool {
@ -247,14 +247,14 @@ impl EpeeValue for BytesMut {
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);
Ok(bytes)
}
fn epee_default_value() -> Option<Self> {
Some(BytesMut::new())
Some(Self::new())
}
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"));
}
ByteArrayVec::try_from(r.copy_to_bytes(len))
.map_err(|_| Error::Format("Field has invalid length"))
Self::try_from(r.copy_to_bytes(len)).map_err(|_| Error::Format("Field has invalid length"))
}
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 {
@ -320,8 +319,7 @@ impl<const N: usize> EpeeValue for ByteArray<N> {
return Err(Error::IO("Not enough bytes to fill object"));
}
ByteArray::try_from(r.copy_to_bytes(N))
.map_err(|_| Error::Format("Field has invalid length"))
Self::try_from(r.copy_to_bytes(N)).map_err(|_| Error::Format("Field has invalid length"))
}
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> {
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 {
@ -343,7 +341,7 @@ impl EpeeValue for String {
}
fn epee_default_value() -> Option<Self> {
Some(String::new())
Some(Self::new())
}
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 mut res = Vec::with_capacity(len);
let mut res = Self::with_capacity(len);
for _ in 0..len {
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> {
Some(Vec::new())
Some(Self::new())
}
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> {
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 len = 1 << (vi_start & 0b11);
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);
@ -67,12 +67,15 @@ pub fn write_varint<B: BufMut>(number: u64, w: &mut B) -> Result<()> {
};
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;
// 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 {
0 => w.put_u8(number as u8),
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};
struct AltName {

View file

@ -1,3 +1,5 @@
#![expect(unused_crate_dependencies, reason = "outer test module")]
use cuprate_epee_encoding::{epee_object, from_bytes};
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};
pub struct Optional {
@ -58,7 +60,7 @@ fn epee_non_default_does_encode() {
let val: Optional = from_bytes(&mut bytes).unwrap();
assert_eq!(val.optional_val, -3);
assert_eq!(val.val, 8)
assert_eq!(val.val, 8);
}
#[test]
@ -70,5 +72,5 @@ fn epee_value_not_present_with_default() {
let val: Optional = from_bytes(&mut bytes).unwrap();
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};
struct Child {
@ -37,6 +39,7 @@ epee_object!(
);
#[test]
#[expect(clippy::float_cmp)]
fn epee_flatten() {
let val2 = ParentChild {
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 std::ops::Deref;
#[derive(Clone)]
struct T {
@ -28,6 +29,6 @@ fn optional_val_in_data() {
];
let t: T = from_bytes(&mut &bytes[..]).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);
}

View file

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

View file

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