From ff358723da641af9f4ae1f742eb1b382f4630220 Mon Sep 17 00:00:00 2001 From: Vika Date: Thu, 22 Jun 2023 20:25:28 +0300 Subject: StorageError: use std::borrow::Cow for msg field This allows avoiding an unnecessary allocation whenever the error message is static. --- kittybox-rs/src/database/mod.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) (limited to 'kittybox-rs/src/database/mod.rs') diff --git a/kittybox-rs/src/database/mod.rs b/kittybox-rs/src/database/mod.rs index db0e360..ea4205c 100644 --- a/kittybox-rs/src/database/mod.rs +++ b/kittybox-rs/src/database/mod.rs @@ -1,4 +1,6 @@ #![warn(missing_docs)] +use std::borrow::Cow; + use async_trait::async_trait; mod file; @@ -122,7 +124,7 @@ pub mod settings { /// Error signalled from the database. #[derive(Debug)] pub struct StorageError { - msg: String, + msg: std::borrow::Cow<'static, str>, source: Option>, kind: ErrorKind, } @@ -137,7 +139,7 @@ impl std::error::Error for StorageError { impl From for StorageError { fn from(err: serde_json::Error) -> Self { Self { - msg: format!("{}", err), + msg: std::borrow::Cow::Owned(format!("{}", err)), source: Some(Box::new(err)), kind: ErrorKind::JsonParsing, } @@ -171,21 +173,33 @@ impl serde::Serialize for StorageError { } impl StorageError { /// Create a new StorageError of an ErrorKind with a message. - fn new(kind: ErrorKind, msg: &str) -> Self { + pub fn new(kind: ErrorKind, msg: String) -> Self { Self { - msg: msg.to_string(), + msg: Cow::Owned(msg), source: None, kind, } } + /// Create a new StorageError of an ErrorKind with a message from + /// a static string. + /// + /// This saves an allocation for a new string and is the preferred + /// way in case the error message doesn't change. + pub fn from_static(kind: ErrorKind, msg: &'static str) -> Self { + Self { + msg: Cow::Borrowed(msg), + source: None, + kind + } + } /// Create a StorageError using another arbitrary Error as a source. - fn with_source( + pub fn with_source( kind: ErrorKind, - msg: &str, + msg: std::borrow::Cow<'static, str>, source: Box, ) -> Self { Self { - msg: msg.to_string(), + msg, source: Some(source), kind, } -- cgit 1.4.1