string_error/
lib.rs

1// Copyright 2017 Ulrich Rhein
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The `string-error` crate.
16//!
17//! This crate provides a simple way to use a string as an error
18//! trait object, i.e. `Box<std::error::Error>`.
19//!
20//! If you need more sophisticated error handling, you should consider
21//! [error-chain](https://crates.io/crates/error-chain), which also provides
22//! functionality to create simple errors from Strings.
23
24use std::fmt;
25use std::error::Error;
26
27/// Wraps `&'static str` and implements the `Error` trait for it.
28#[derive(Debug)]
29struct StaticStrError {
30    error: &'static str
31}
32
33impl Error for StaticStrError {
34    fn description(&self) -> &str {
35        self.error
36    }
37}
38
39impl fmt::Display for StaticStrError {
40    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41        f.write_str(self.error)
42    }
43}
44
45/// Wraps an owned `String` and implements the `Error` trait for it.
46#[derive(Debug)]
47struct StringError {
48    error: String
49}
50
51impl Error for StringError {
52    fn description(&self) -> &str {
53        &self.error
54    }
55}
56
57impl fmt::Display for StringError {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        write!(f, "Error: {}", self.error)
60    }
61}
62
63/// Creates an error trait object for a string constant (`&'static str`).
64///
65/// # Examples
66///
67/// ```
68/// use string_error::*;
69///
70/// let x = static_err("Foo");
71/// assert_eq!(x.description(), "Foo");
72/// ```
73pub fn static_err(e: &'static str) -> Box<Error> {
74    Box::new(StaticStrError { error: e })
75}
76
77/// Creates an error trait object for a string (`&str`).
78///
79/// This copies the argument into an owned string. To avoid the copy, use
80/// either `into_err` or `static_err`.
81/// 
82/// # Examples
83///
84/// ```
85/// use string_error::*;
86///
87/// let x = new_err("Foo");
88/// assert_eq!(x.description(), "Foo");
89/// ```
90pub fn new_err(e: &str) -> Box<Error> {
91    Box::new(StringError { error: String::from(e) })
92}
93
94/// Creates an error trait object for an owned string (`String`).
95///
96/// This takes ownership of the `String` argument.
97///
98/// # Examples
99///
100/// ```
101/// use string_error::*;
102///
103/// let x = into_err(String::from("Foo"));
104/// assert_eq!(x.description(), "Foo");
105/// ```
106pub fn into_err(e: String) -> Box<Error> {
107    Box::new(StringError { error: e })
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    static SOME_STRING : &'static str = "This is a String?!";
114
115    #[test]
116    fn test_static_err() {
117        let x = static_err(SOME_STRING);
118        assert_eq!(x.description(), SOME_STRING);
119        assert!(x.cause().is_none());
120    }
121
122    #[test]
123    fn test_new_err() {
124        let x = new_err(SOME_STRING);
125        assert_eq!(x.description(), SOME_STRING);
126        assert!(x.cause().is_none());
127    }
128
129    #[test]
130    fn test_into_err() {
131        let x = into_err(String::from(SOME_STRING));
132        assert_eq!(x.description(), SOME_STRING);
133        assert!(x.cause().is_none());
134    }
135}