dragonfly_client_core/error/message.rs
1/*
2 * Copyright 2024 The Dragonfly Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::borrow::Cow;
18
19/// The message for the error.
20#[derive(Debug)]
21pub struct Message(Cow<'static, str>);
22
23/// From<&'static str> for Message implements the conversion from &'static str to Message.
24impl From<&'static str> for Message {
25 /// Returns the message from the string.
26 fn from(s: &'static str) -> Self {
27 Message(Cow::Borrowed(s))
28 }
29}
30
31/// From<String> for Message implements the conversion from String to Message.
32impl From<String> for Message {
33 /// Returns the message from the string.
34 fn from(s: String) -> Self {
35 Message(Cow::Owned(s))
36 }
37}
38
39/// Implements the message for the error.
40impl Message {
41 /// Returns the string of the message.
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn from_str_and_string_preserve_text() {
53 let test_cases: Vec<(Message, &str)> = vec![
54 ("hello".into(), "hello"),
55 ("world".to_string().into(), "world"),
56 ];
57
58 for (message, expected) in test_cases {
59 assert_eq!(message.as_str(), expected);
60 }
61 }
62}