Skip to content

Commit

Permalink
Remove clone derive on errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Tehforsch committed Nov 11, 2024
1 parent d31835d commit 1adfac7
Show file tree
Hide file tree
Showing 22 changed files with 61 additions and 87 deletions.
4 changes: 2 additions & 2 deletions rust/src/feed/update/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use thiserror::Error;

use crate::feed::{verify, VerifyError};

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
/// Errors within feed handling
pub enum ErrorKind {
/// An InterpretError occurred while interpreting
Expand All @@ -32,7 +32,7 @@ pub enum ErrorKind {
VerifyError(#[from] verify::Error),
}

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
#[error("Error with key '{key}': {kind}")]
/// ErrorKind and key of error
pub struct Error {
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/cryptographic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub mod hmac;
#[cfg(test)]
mod tests;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
pub enum CryptographicError {
#[error("Error in AesGcm: insufficient buffer size.")]
InsufficientBufferSize,
Expand Down
8 changes: 4 additions & 4 deletions rust/src/nasl/builtin/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::knowledge_base::KBError;
use super::regex::RegexError;
use super::{misc::MiscError, network::socket::SocketError, ssh::SshError, string::StringError};

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
pub enum BuiltinError {
#[error("{0}")]
Ssh(SshError),
Expand Down Expand Up @@ -52,11 +52,11 @@ macro_rules! builtin_error_variant (
}
}

impl TryFrom<FnError> for $err {
impl<'a> TryFrom<&'a FnError> for &'a $err {
type Error = ();

fn try_from(value: FnError) -> Result<Self, Self::Error> {
match value.kind {
fn try_from(value: &'a FnError) -> Result<Self, Self::Error> {
match &value.kind {
FnErrorKind::Builtin(
BuiltinError::$variant(e)
) => Ok(e),
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/http/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::io;

use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[derive(Debug, Error)]
pub enum HttpError {
#[error("IO error during HTTP: {0}")]
IO(io::ErrorKind),
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/isotime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::nasl::prelude::*;
use chrono::{Datelike, Months, NaiveDate, NaiveDateTime, TimeDelta};
use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[derive(Debug, Error)]
#[error("{0}")]
pub struct IsotimeError(String);

Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/knowledge_base/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::storage::{Field, Kb, Retrieve};
use nasl_function_proc_macro::nasl_function;
use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[derive(Debug, Error)]
#[error("{0}")]
pub struct KBError(String);

Expand Down
14 changes: 2 additions & 12 deletions rust/src/nasl/builtin/misc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,14 @@ use flate2::{
read::GzDecoder, read::ZlibDecoder, write::GzEncoder, write::ZlibEncoder, Compression,
};

#[derive(Debug, Clone, Error)]
// It would be nicer to derive this using #[from] from
// thiserror, but io::Error does not impl `Clone`,
// so we wrap `io::ErrorKind` instead, which
// does not impl `Error` which is why this `From` impl exists.
#[derive(Debug, Error)]
pub enum MiscError {
#[error("IO Error: {0}")]
IO(io::ErrorKind),
IO(#[from] io::Error),
#[error("Encountered time before 1970. {0}")]
TimeBefore1970(String),
}

impl From<io::Error> for MiscError {
fn from(value: io::Error) -> Self {
Self::IO(value.kind())
}
}

#[inline]
#[cfg(unix)]
/// Reads 8 bytes from /dev/urandom and parses it to an i64
Expand Down
26 changes: 9 additions & 17 deletions rust/src/nasl/builtin/network/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,13 @@ use super::{
// Number of times to resend a UDP packet, when no response is received
const NUM_TIMES_TO_RESEND: usize = 5;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
#[error("{0}")]
// It would be nicer to derive this using #[from] from
// thiserror, but io::Error does not impl `Clone`,
// so we wrap `io::ErrorKind` instead, which
// does not impl `Error` which is why this `From` impl exists.
pub enum SocketError {
IO(std::io::ErrorKind),
IO(#[from] std::io::Error),
Diagnostic(String, Option<NaslValue>),
}

impl From<io::Error> for SocketError {
fn from(value: io::Error) -> Self {
Self::IO(value.kind())
}
}

pub struct Interval {
interval: Duration,
last_tick: SystemTime,
Expand Down Expand Up @@ -445,8 +435,8 @@ impl NaslSockets {
io::ErrorKind::TimedOut => {
conn.socket.send(&conn.buffer).map_err(SocketError::from)?;
}
kind => {
ret = Err(SocketError::IO(kind));
_ => {
ret = Err(SocketError::IO(e));
break;
}
},
Expand Down Expand Up @@ -671,8 +661,10 @@ impl NaslSockets {
match Self::open_tcp(addr, port, bufsz, timeout, tls_config.as_ref()) {
Ok(socket) => return Ok(socket),
Err(err) => {
if !matches!(err, SocketError::IO(io::ErrorKind::TimedOut)) {
return Err(err.into());
if let SocketError::IO(ref io_err) = err {
if io_err.kind() == io::ErrorKind::TimedOut {
return Err(err.into());
}
}
retry -= 1;
}
Expand All @@ -683,7 +675,7 @@ impl NaslSockets {
// 2. Log too many timeouts
// 3. Create result of type error with:
// ERRMSG|||<IP>|||<vhost>|||<port>/tcp||| ||| Too many timeouts. The port was set to closed
Err(SocketError::IO(io::ErrorKind::TimedOut).into())
Err(SocketError::IO(io::ErrorKind::TimedOut.into()).into())
}

fn load_private_key(filename: &str) -> Result<PrivateKeyDer<'static>, SocketError> {
Expand Down
4 changes: 2 additions & 2 deletions rust/src/nasl/builtin/raw_ip/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use packet_forgery::PacketForgery;
pub use packet_forgery::PacketForgeryError;
use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[derive(Debug, Error)]
pub enum RawIpError {
#[error("Failed to get local MAC address.")]
FailedToGetLocalMacAddress,
Expand All @@ -24,7 +24,7 @@ pub enum RawIpError {
#[error("Invalid IP address.")]
InvalidIpAddress,
#[error("Failed to bind.")]
FailedToBind(io::ErrorKind),
FailedToBind(io::Error),
#[error("No route to destination.")]
NoRouteToDestination,
}
Expand Down
6 changes: 3 additions & 3 deletions rust/src/nasl/builtin/raw_ip/packet_forgery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ use socket2::{Domain, Protocol, Socket};
use thiserror::Error;
use tracing::debug;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
pub enum PacketForgeryError {
#[error("{0}")]
Custom(String),
#[error("Failed to parse socket address. {0}")]
ParseSocketAddr(std::net::AddrParseError),
#[error("Failed to send packet. {0}")]
SendPacket(std::io::ErrorKind),
SendPacket(std::io::Error),
}

fn error(s: String) -> FnError {
Expand Down Expand Up @@ -2074,7 +2074,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result<NaslValue,
debug!("Sent {} bytes", b);
}
Err(e) => {
return Err(PacketForgeryError::SendPacket(e.kind()).into());
return Err(PacketForgeryError::SendPacket(e).into());
}
}

Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/raw_ip/raw_ip_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub fn bind_local_socket(dst: &SocketAddr) -> Result<UdpSocket, RawIpError> {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0"),
SocketAddr::V6(_) => UdpSocket::bind(" 0:0:0:0:0:0:0:0:0"),
}
.map_err(|e| RawIpError::FailedToBind(e.kind()))
.map_err(|e| RawIpError::FailedToBind(e))
}

/// Return the source IP address given the destination IP address
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/regex/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::nasl::prelude::*;
use regex::{Regex, RegexBuilder};
use thiserror::Error;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
pub enum RegexError {
#[error("Error building regular expression pattern: {0}")]
BuildingError(regex::Error),
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/ssh/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl From<russh::Error> for LibError {
}
}

#[derive(Clone, Debug, Error)]
#[derive(Debug, Error)]
pub struct SshError {
pub kind: SshErrorKind,
id: Option<SessionId>,
Expand Down
2 changes: 1 addition & 1 deletion rust/src/nasl/builtin/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::nasl::prelude::*;

use super::BuiltinError;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
#[error("{0}")]
pub struct StringError(#[from] std::fmt::Error);

Expand Down
6 changes: 3 additions & 3 deletions rust/src/nasl/interpreter/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::nasl::syntax::{Statement, SyntaxError, TokenCategory};
use crate::nasl::utils::error::FnError;
use thiserror::Error;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
/// An error that occurred while calling a function
#[error("Error while calling function '{function}': {kind}")]
pub struct FunctionCallError {
Expand All @@ -32,7 +32,7 @@ impl FunctionCallError {
}
}

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
/// Is used to represent an error while interpreting
#[error("{} {kind}", self.format_origin())]
pub struct InterpretError {
Expand Down Expand Up @@ -63,7 +63,7 @@ impl InterpretError {
}
}

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
/// Is used to give hints to the user how to react on an error while interpreting
pub enum InterpretErrorKind {
/// When returned context is a function when a value is required.
Expand Down
12 changes: 6 additions & 6 deletions rust/src/nasl/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ use super::{
// The following exists to trick the trait solver into
// believing me that everything is fine. Doing this naively
// runs into some compiler errors.
trait CloneableFn: Fn(NaslResult) -> bool {
trait CloneableFn: Fn(&NaslResult) -> bool {
fn clone_box<'a>(&self) -> Box<dyn 'a + CloneableFn>
where
Self: 'a;
}

impl<F> CloneableFn for F
where
F: Fn(NaslResult) -> bool + Clone,
F: Fn(&NaslResult) -> bool + Clone,
{
fn clone_box<'a>(&self) -> Box<dyn 'a + CloneableFn>
where
Expand Down Expand Up @@ -184,7 +184,7 @@ where
pub fn check(
&mut self,
line: impl Into<String>,
f: impl Fn(NaslResult) -> bool + 'static + Clone,
f: impl Fn(&NaslResult) -> bool + 'static + Clone,
expected: Option<impl Into<String>>,
) -> &mut Self {
self.add_line(
Expand Down Expand Up @@ -323,7 +323,7 @@ where
fn compare_result(&self, result: &Result<NaslValue, FnError>, reference: &TestResult) -> bool {
match reference {
TestResult::Ok(val) => result.as_ref().unwrap() == val,
TestResult::GenericCheck(f, _) => f(result.clone()),
TestResult::GenericCheck(f, _) => f(result),
TestResult::None => true,
}
}
Expand Down Expand Up @@ -391,14 +391,14 @@ macro_rules! check_err_matches {
|e| {
if let Err(e) = e {
// Convert with try_into to allow using
// the variants of `FnError` directly without
// the variants of `FnErrorKind` directly without
// having to wrap them in the outer enum.
let converted = e.try_into();
// This is only irrefutable for the
// FnError -> FnError conversion but not for others.
#[allow(irrefutable_let_patterns)]
if let Ok(e) = converted {
matches!(e, $pat)
matches!(e, &$pat)
} else {
false
}
Expand Down
22 changes: 11 additions & 11 deletions rust/src/nasl/utils/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::nasl::prelude::NaslValue;

use crate::storage::StorageError;

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
#[error("{kind}")]
pub struct FnError {
#[source]
Expand Down Expand Up @@ -75,7 +75,7 @@ impl From<InternalError> for FnError {
}
}

#[derive(Debug, Clone, Error)]
#[derive(Debug, Error)]
pub enum FnErrorKind {
#[error("{0}")]
Argument(ArgumentError),
Expand Down Expand Up @@ -127,33 +127,33 @@ impl From<StorageError> for FnError {
}
}

impl TryFrom<FnError> for ArgumentError {
impl<'a> TryFrom<&'a FnError> for &'a ArgumentError {
type Error = ();

fn try_from(value: FnError) -> Result<Self, Self::Error> {
match value.kind {
fn try_from(value: &'a FnError) -> Result<Self, Self::Error> {
match &value.kind {
FnErrorKind::Argument(e) => Ok(e),
_ => Err(()),
}
}
}

impl TryFrom<FnError> for InternalError {
impl<'a> TryFrom<&'a FnError> for &'a InternalError {
type Error = ();

fn try_from(value: FnError) -> Result<Self, Self::Error> {
match value.kind {
fn try_from(value: &'a FnError) -> Result<Self, Self::Error> {
match &value.kind {
FnErrorKind::Internal(e) => Ok(e),
_ => Err(()),
}
}
}

impl TryFrom<FnError> for BuiltinError {
impl<'a> TryFrom<&'a FnError> for &'a BuiltinError {
type Error = ();

fn try_from(value: FnError) -> Result<Self, Self::Error> {
match value.kind {
fn try_from(value: &'a FnError) -> Result<Self, Self::Error> {
match &value.kind {
FnErrorKind::Builtin(e) => Ok(e),
_ => Err(()),
}
Expand Down
Loading

0 comments on commit 1adfac7

Please sign in to comment.