diff options
author | Vika <vika@fireburn.ru> | 2023-06-22 20:25:28 +0300 |
---|---|---|
committer | Vika <vika@fireburn.ru> | 2023-06-22 20:25:28 +0300 |
commit | ff358723da641af9f4ae1f742eb1b382f4630220 (patch) | |
tree | 32a2319a0bea909b9d267e44fa3a632991ddda12 /kittybox-rs/src/database/mod.rs | |
parent | 0285e630f3cae1ee2df2c7c465998b1ce669944f (diff) | |
download | kittybox-ff358723da641af9f4ae1f742eb1b382f4630220.tar.zst |
StorageError: use std::borrow::Cow for msg field
This allows avoiding an unnecessary allocation whenever the error message is static.
Diffstat (limited to 'kittybox-rs/src/database/mod.rs')
-rw-r--r-- | kittybox-rs/src/database/mod.rs | 28 |
1 files changed, 21 insertions, 7 deletions
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<Box<dyn std::error::Error + Send + Sync>>, kind: ErrorKind, } @@ -137,7 +139,7 @@ impl std::error::Error for StorageError { impl From<serde_json::Error> 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<dyn std::error::Error + Send + Sync>, ) -> Self { Self { - msg: msg.to_string(), + msg, source: Some(source), kind, } |