sabre_sdk/
protos.rs

1// Copyright 2018 Bitwise IO, Inc.
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
15use std::error::Error as StdError;
16
17#[derive(Debug)]
18pub enum ProtoConversionError {
19    SerializationError(String),
20    InvalidTypeError(String),
21}
22
23impl StdError for ProtoConversionError {
24    fn description(&self) -> &str {
25        match *self {
26            ProtoConversionError::SerializationError(ref msg) => msg,
27            ProtoConversionError::InvalidTypeError(ref msg) => msg,
28        }
29    }
30}
31
32impl std::fmt::Display for ProtoConversionError {
33    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
34        match *self {
35            ProtoConversionError::SerializationError(ref s) => {
36                write!(f, "SerializationError: {}", s)
37            }
38            ProtoConversionError::InvalidTypeError(ref s) => write!(f, "InvalidTypeError: {}", s),
39        }
40    }
41}
42
43pub trait FromProto<P>: Sized {
44    fn from_proto(other: P) -> Result<Self, ProtoConversionError>;
45}
46
47pub trait FromNative<N>: Sized {
48    fn from_native(other: N) -> Result<Self, ProtoConversionError>;
49}
50
51pub trait FromBytes<N>: Sized {
52    fn from_bytes(bytes: &[u8]) -> Result<N, ProtoConversionError>;
53}
54
55pub trait IntoBytes: Sized {
56    fn into_bytes(self) -> Result<Vec<u8>, ProtoConversionError>;
57}
58
59pub trait IntoNative<T>: Sized
60where
61    T: FromProto<Self>,
62{
63    fn into_native(self) -> Result<T, ProtoConversionError> {
64        FromProto::from_proto(self)
65    }
66}
67
68pub trait IntoProto<T>: Sized
69where
70    T: FromNative<Self>,
71{
72    fn into_proto(self) -> Result<T, ProtoConversionError> {
73        FromNative::from_native(self)
74    }
75}
76
77// Includes the autogenerated protobuf messages
78include!(concat!(env!("OUT_DIR"), "/protos/mod.rs"));