tetsy_unexpected/
lib.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy Vapory.
3
4// Tetsy Vapory is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy Vapory is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Error utils
18
19use std::fmt;
20
21#[derive(Debug, PartialEq, Eq, Clone, Copy)]
22/// Error indicating an expected value was not found.
23pub struct Mismatch<T> {
24	/// Value expected.
25	pub expected: T,
26	/// Value found.
27	pub found: T,
28}
29
30impl<T: fmt::Display> fmt::Display for Mismatch<T> {
31	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32		f.write_fmt(format_args!("Expected {}, found {}", self.expected, self.found))
33	}
34}
35
36#[derive(Debug, PartialEq, Eq, Clone, Copy)]
37/// Error indicating value found is outside of a valid range.
38pub struct OutOfBounds<T> {
39	/// Minimum allowed value.
40	pub min: Option<T>,
41	/// Maximum allowed value.
42	pub max: Option<T>,
43	/// Value found.
44	pub found: T,
45}
46
47impl<T> OutOfBounds<T> {
48	pub fn map<F, U>(self, map: F) -> OutOfBounds<U>
49		where F: Fn(T) -> U
50	{
51		OutOfBounds {
52			min: self.min.map(&map),
53			max: self.max.map(&map),
54			found: map(self.found),
55		}
56	}
57}
58
59impl<T: fmt::Display> fmt::Display for OutOfBounds<T> {
60	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61		let msg = match (self.min.as_ref(), self.max.as_ref()) {
62			(Some(min), Some(max)) => format!("Min={}, Max={}", min, max),
63			(Some(min), _) => format!("Min={}", min),
64			(_, Some(max)) => format!("Max={}", max),
65			(None, None) => "".into(),
66		};
67
68		f.write_fmt(format_args!("Value {} out of bounds. {}", self.found, msg))
69	}
70}