Skip to content

Remove allow(clippy::result_unit_err) #533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Changed

- Changed the error type of these methods from `()` to `CapacityError`.
- `String::push_str`
- `String::push`
- `Vec::extend_from_slice`
- `Vec::from_slice`
- `Vec::resize_default`
- `Vec::resize`
- Renamed `FromUtf16Error::DecodeUtf16Error` to `FromUtf16Error::DecodeUtf16`.
- Changed `stable_deref_trait` to a platform-dependent dependency.
- Changed `SortedLinkedList::pop` return type from `Result<T, ()>` to `Option<T>` to match `std::vec::pop`.
- `Vec::capacity` is no longer a `const` function.
Expand Down
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,16 @@ mod ufmt;
pub mod _export {
pub use crate::string::format;
}

/// The error type for fallible [`Vec`] and [`String`] methods.
#[derive(Debug)]
#[non_exhaustive]
pub struct CapacityError;

impl core::fmt::Display for CapacityError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("insufficient capacity")
}
}

impl core::error::Error for CapacityError {}
58 changes: 33 additions & 25 deletions src/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use core::{
};

use crate::vec::{OwnedVecStorage, Vec, VecInner, VecStorage, ViewVecStorage};
use crate::CapacityError;

mod drain;
pub use drain::Drain;
Expand All @@ -24,20 +25,28 @@ pub use drain::Drain;
#[derive(Debug)]
pub enum FromUtf16Error {
/// The capacity of the `String` is too small for the given operation.
Capacity,
Capacity(CapacityError),
/// Error decoding UTF-16.
DecodeUtf16Error(DecodeUtf16Error),
DecodeUtf16(DecodeUtf16Error),
}

impl fmt::Display for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Capacity => "insufficient capacity".fmt(f),
Self::DecodeUtf16Error(e) => write!(f, "invalid UTF-16: {}", e),
Self::Capacity(err) => write!(f, "{err}"),
Self::DecodeUtf16(err) => write!(f, "invalid UTF-16: {err}"),
}
}
}

impl core::error::Error for FromUtf16Error {}

impl From<CapacityError> for FromUtf16Error {
fn from(e: CapacityError) -> Self {
Self::Capacity(e)
}
}

/// Base struct for [`String`] and [`StringView`], generic over the [`VecStorage`].
///
/// In most cases you should use [`String`] or [`StringView`] directly. Only use this
Expand Down Expand Up @@ -164,10 +173,10 @@ impl<const N: usize> String<N> {
for c in char::decode_utf16(v.iter().cloned()) {
match c {
Ok(c) => {
s.push(c).map_err(|_| FromUtf16Error::Capacity)?;
s.push(c).map_err(|_| CapacityError)?;
}
Err(err) => {
return Err(FromUtf16Error::DecodeUtf16Error(err));
return Err(FromUtf16Error::DecodeUtf16(err));
}
}
}
Expand Down Expand Up @@ -253,7 +262,7 @@ impl<const N: usize> String<N> {
/// assert!(b.len() == 2);
///
/// assert_eq!(&[b'a', b'b'], &b[..]);
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
pub fn into_bytes(self) -> Vec<u8, N> {
Expand Down Expand Up @@ -360,7 +369,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
///
/// let _s = s.as_str();
/// // s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
pub fn as_str(&self) -> &str {
Expand All @@ -379,7 +388,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// let mut s: String<4> = String::try_from("ab")?;
/// let s = s.as_mut_str();
/// s.make_ascii_uppercase();
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
Expand Down Expand Up @@ -411,7 +420,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// vec.reverse();
/// }
/// assert_eq!(s, "olleh");
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
pub unsafe fn as_mut_vec(&mut self) -> &mut VecInner<u8, S> {
&mut self.vec
Expand All @@ -433,11 +442,10 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// assert_eq!("foobar", s);
///
/// assert!(s.push_str("tender").is_err());
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
#[allow(clippy::result_unit_err)]
pub fn push_str(&mut self, string: &str) -> Result<(), ()> {
pub fn push_str(&mut self, string: &str) -> Result<(), CapacityError> {
self.vec.extend_from_slice(string.as_bytes())
}

Expand Down Expand Up @@ -476,13 +484,12 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// assert!("abc123" == s.as_str());
///
/// assert_eq!("abc123", s);
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
#[allow(clippy::result_unit_err)]
pub fn push(&mut self, c: char) -> Result<(), ()> {
pub fn push(&mut self, c: char) -> Result<(), CapacityError> {
match c.len_utf8() {
1 => self.vec.push(c as u8).map_err(|_| {}),
1 => self.vec.push(c as u8).map_err(|_| CapacityError),
_ => self
.vec
.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
Expand Down Expand Up @@ -513,7 +520,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// s.truncate(2);
///
/// assert_eq!("he", s);
/// # Ok::<(), ()>(())
/// # Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
pub fn truncate(&mut self, new_len: usize) {
Expand Down Expand Up @@ -541,7 +548,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// assert_eq!(s.pop(), Some('f'));
///
/// assert_eq!(s.pop(), None);
/// Ok::<(), ()>(())
/// Ok::<(), heapless::CapacityError>(())
/// ```
pub fn pop(&mut self) -> Option<char> {
let ch = self.chars().next_back()?;
Expand Down Expand Up @@ -615,7 +622,7 @@ impl<S: VecStorage<u8> + ?Sized> StringInner<S> {
/// assert!(s.is_empty());
/// assert_eq!(0, s.len());
/// assert_eq!(8, s.capacity());
/// Ok::<(), ()>(())
/// Ok::<(), heapless::CapacityError>(())
/// ```
#[inline]
pub fn clear(&mut self) {
Expand All @@ -630,7 +637,8 @@ impl<const N: usize> Default for String<N> {
}

impl<'a, const N: usize> TryFrom<&'a str> for String<N> {
type Error = ();
type Error = CapacityError;

fn try_from(s: &'a str) -> Result<Self, Self::Error> {
let mut new = Self::new();
new.push_str(s)?;
Expand All @@ -639,7 +647,7 @@ impl<'a, const N: usize> TryFrom<&'a str> for String<N> {
}

impl<const N: usize> str::FromStr for String<N> {
type Err = ();
type Err = CapacityError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut new = Self::new();
Expand Down Expand Up @@ -912,7 +920,7 @@ impl_try_from_num!(u64, 20);

#[cfg(test)]
mod tests {
use crate::{String, Vec};
use crate::{CapacityError, String, Vec};

#[test]
fn static_new() {
Expand Down Expand Up @@ -980,7 +988,7 @@ mod tests {
assert!(s.len() == 3);
assert_eq!(s, "123");

let _: () = String::<2>::try_from("123").unwrap_err();
let _: CapacityError = String::<2>::try_from("123").unwrap_err();
}

#[test]
Expand All @@ -991,7 +999,7 @@ mod tests {
assert!(s.len() == 3);
assert_eq!(s, "123");

let _: () = String::<2>::from_str("123").unwrap_err();
let _: CapacityError = String::<2>::from_str("123").unwrap_err();
}

#[test]
Expand Down
5 changes: 3 additions & 2 deletions src/ufmt.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
use crate::{
string::StringInner,
vec::{VecInner, VecStorage},
CapacityError,
};
use ufmt_write::uWrite;

impl<S: VecStorage<u8> + ?Sized> uWrite for StringInner<S> {
type Error = ();
type Error = CapacityError;
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.push_str(s)
}
}

impl<S: VecStorage<u8> + ?Sized> uWrite for VecInner<u8, S> {
type Error = ();
type Error = CapacityError;
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.extend_from_slice(s.as_bytes())
}
Expand Down
22 changes: 10 additions & 12 deletions src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use core::{
slice,
};

use crate::CapacityError;

mod drain;

mod storage {
Expand Down Expand Up @@ -192,8 +194,7 @@ impl<T, const N: usize> Vec<T, N> {
/// let mut v: Vec<u8, 16> = Vec::new();
/// v.extend_from_slice(&[1, 2, 3]).unwrap();
/// ```
#[allow(clippy::result_unit_err)]
pub fn from_slice(other: &[T]) -> Result<Self, ()>
pub fn from_slice(other: &[T]) -> Result<Self, CapacityError>
where
T: Clone,
{
Expand Down Expand Up @@ -516,22 +517,21 @@ impl<T, S: VecStorage<T> + ?Sized> VecInner<T, S> {
/// vec.extend_from_slice(&[2, 3, 4]).unwrap();
/// assert_eq!(*vec, [1, 2, 3, 4]);
/// ```
#[allow(clippy::result_unit_err)]
pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>
pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
where
T: Clone,
{
pub fn extend_from_slice_inner<T>(
len: &mut usize,
buf: &mut [MaybeUninit<T>],
other: &[T],
) -> Result<(), ()>
) -> Result<(), CapacityError>
where
T: Clone,
{
if *len + other.len() > buf.len() {
// won't fit in the `Vec`; don't modify anything and return an error
Err(())
Err(CapacityError)
} else {
for elem in other {
unsafe { *buf.get_unchecked_mut(*len) = MaybeUninit::new(elem.clone()) }
Expand Down Expand Up @@ -626,13 +626,12 @@ impl<T, S: VecStorage<T> + ?Sized> VecInner<T, S> {
/// `new_len` is less than len, the Vec is simply truncated.
///
/// See also [`resize_default`](Self::resize_default).
#[allow(clippy::result_unit_err)]
pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>
pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), CapacityError>
where
T: Clone,
{
if new_len > self.capacity() {
return Err(());
return Err(CapacityError);
}

if new_len > self.len {
Expand All @@ -653,8 +652,7 @@ impl<T, S: VecStorage<T> + ?Sized> VecInner<T, S> {
/// If `new_len` is less than `len`, the `Vec` is simply truncated.
///
/// See also [`resize`](Self::resize).
#[allow(clippy::result_unit_err)]
pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
pub fn resize_default(&mut self, new_len: usize) -> Result<(), CapacityError>
where
T: Clone + Default,
{
Expand Down Expand Up @@ -1211,7 +1209,7 @@ impl<T, S: VecStorage<T> + ?Sized> Drop for VecInner<T, S> {
}

impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N> {
type Error = ();
type Error = CapacityError;

fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
Self::from_slice(slice)
Expand Down