grid_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    fn cause(&self) -> Option<&dyn StdError> {
32        match *self {
33            ProtoConversionError::SerializationError(_) => None,
34            ProtoConversionError::InvalidTypeError(_) => None,
35        }
36    }
37}
38
39impl std::fmt::Display for ProtoConversionError {
40    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
41        match *self {
42            ProtoConversionError::SerializationError(ref s) => {
43                write!(f, "SerializationError: {}", s)
44            }
45            ProtoConversionError::InvalidTypeError(ref s) => write!(f, "InvalidTypeError: {}", s),
46        }
47    }
48}
49
50pub trait FromProto<P>: Sized {
51    fn from_proto(other: P) -> Result<Self, ProtoConversionError>;
52}
53
54pub trait FromNative<N>: Sized {
55    fn from_native(other: N) -> Result<Self, ProtoConversionError>;
56}
57
58pub trait FromBytes<N>: Sized {
59    fn from_bytes(bytes: &[u8]) -> Result<N, ProtoConversionError>;
60}
61
62pub trait IntoBytes: Sized {
63    fn into_bytes(self) -> Result<Vec<u8>, ProtoConversionError>;
64}
65
66pub trait IntoNative<T>: Sized
67where
68    T: FromProto<Self>,
69{
70    fn into_native(self) -> Result<T, ProtoConversionError> {
71        FromProto::from_proto(self)
72    }
73}
74
75pub trait IntoProto<T>: Sized
76where
77    T: FromNative<Self>,
78{
79    fn into_proto(self) -> Result<T, ProtoConversionError> {
80        FromNative::from_native(self)
81    }
82}
83
84// Includes the autogenerated protobuf messages
85include!(concat!(env!("OUT_DIR"), "/protos/mod.rs"));