tink_core/utils.rs
1// Copyright 2020 The Tink-Rust Authors
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////////////////////////////////////////////////////////////////////////////////
16
17//! Utilities for Tink Rust code.
18//!
19//! Some of these utilities are not idiomatic Rust, but are included to make the process of
20//! translating code from other languages (e.g. Go) easier.
21
22use std::error::Error;
23
24/// `Error` type for errors emitted by Tink. Note that errors from cryptographic
25/// operations are necessarily uninformative, to avoid information leakage.
26#[derive(Debug)]
27pub struct TinkError {
28 msg: String,
29 src: Option<Box<dyn Error + Send>>,
30}
31
32impl TinkError {
33 pub fn new(msg: &str) -> Self {
34 msg.into()
35 }
36}
37
38impl std::fmt::Display for TinkError {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 if let Some(src) = &self.src {
41 write!(f, "{}: {}", self.msg, src)
42 } else {
43 write!(f, "{}", self.msg)
44 }
45 }
46}
47
48impl Error for TinkError {}
49
50impl std::convert::From<&str> for TinkError {
51 fn from(msg: &str) -> Self {
52 TinkError {
53 msg: msg.to_string(),
54 src: None,
55 }
56 }
57}
58
59impl std::convert::From<String> for TinkError {
60 fn from(msg: String) -> Self {
61 TinkError { msg, src: None }
62 }
63}
64
65/// Wrap an error with an additional message. This utility is intended to help
66/// with porting Go code to Rust, to cover patterns like:
67///
68/// ```Go
69/// thing, err := FunctionCall()
70/// if err != nil {
71/// return nil, fmt.Errorf("FunctionCall failed: %s", err)
72/// }
73/// ```
74pub fn wrap_err<T>(msg: &str, src: T) -> TinkError
75where
76 T: Error + Send + 'static,
77{
78 TinkError {
79 msg: msg.to_string(),
80 src: Some(Box::new(src)),
81 }
82}