Skip to content

Commit

Permalink
Implement trivial Copy and ToOwned functions for Error<_> (#1788)
Browse files Browse the repository at this point in the history
* Implement trivial Copy and ToOwned functions for Error<I>

* Update src/error.rs

---------

Co-authored-by: Geoffroy Couprie <[email protected]>
Co-authored-by: Geoffroy Couprie <[email protected]>
  • Loading branch information
3 people authored Dec 8, 2024
1 parent 5281128 commit ebb9e47
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,48 @@ impl<I: fmt::Display> fmt::Display for Error<I> {
}
}

#[cfg(feature = "alloc")]
impl<I: ToOwned + ?Sized> Error<&I> {
/// Converts `Error<&I>` into `Error<I::Owned>` by cloning.
pub fn cloned(self) -> Error<I::Owned> {
Error {
input: self.input.to_owned(),
code: self.code,
}
}
}

#[cfg(feature = "alloc")]
impl<I: ToOwned + ?Sized> Error<&mut I> {
/// Converts `Error<&mut I>` into `Error<I::Owned>` by cloning.
pub fn cloned(self) -> Error<I::Owned> {
Error {
input: self.input.to_owned(),
code: self.code,
}
}
}

impl<I: Copy> Error<&I> {
/// Converts `Error<&I>` into `Error<I>` by copying.
pub fn copied(self) -> Error<I> {
Error {
input: *self.input,
code: self.code,
}
}
}

impl<I: Copy> Error<&mut I> {
/// Converts `Error<&mut I>` into `Error<I>` by copying.
pub fn copied(self) -> Error<I> {
Error {
input: *self.input,
code: self.code,
}
}
}

#[cfg(feature = "std")]
impl<I: fmt::Debug + fmt::Display> std::error::Error for Error<I> {}

Expand Down Expand Up @@ -756,6 +798,28 @@ mod tests {

let _result: IResult<_, _, VerboseError<&str>> = char('x')(input);
}

#[cfg(feature = "alloc")]
#[test]
fn clone_error() {
use crate::lib::std::string::String;
let err = Error {
code: ErrorKind::Eof,
input: "test",
};

let _err: Error<String> = err.cloned();
}

#[test]
fn copy_error() {
let err = Error {
code: ErrorKind::Eof,
input: &0_u8,
};

let _err: Error<u8> = err.copied();
}
}

/*
Expand Down

0 comments on commit ebb9e47

Please sign in to comment.