containerd_snapshots/
convert.rs

1/*
2   Copyright The containerd Authors.
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17//! Various conversions between GRPC and native types.
18
19use std::convert::{TryFrom, TryInto};
20
21use thiserror::Error;
22use tonic::Status;
23
24use crate::{api::snapshots::v1 as grpc, Info, Kind};
25
26impl From<Kind> for i32 {
27    fn from(kind: Kind) -> i32 {
28        match kind {
29            Kind::Unknown => 0,
30            Kind::View => 1,
31            Kind::Active => 2,
32            Kind::Committed => 3,
33        }
34    }
35}
36
37impl TryFrom<i32> for Kind {
38    type Error = Error;
39
40    fn try_from(value: i32) -> Result<Self, Self::Error> {
41        Ok(match value {
42            0 => Kind::Unknown,
43            1 => Kind::View,
44            2 => Kind::Active,
45            3 => Kind::Committed,
46            _ => return Err(Error::InvalidEnumValue(value)),
47        })
48    }
49}
50
51impl TryFrom<grpc::Info> for Info {
52    type Error = Error;
53
54    fn try_from(info: grpc::Info) -> Result<Self, Self::Error> {
55        Ok(Info {
56            kind: info.kind.try_into()?,
57            name: info.name,
58            parent: info.parent,
59            labels: info.labels,
60            created_at: info.created_at.unwrap_or_default().try_into()?,
61            updated_at: info.updated_at.unwrap_or_default().try_into()?,
62        })
63    }
64}
65
66impl From<Info> for grpc::Info {
67    fn from(info: Info) -> Self {
68        grpc::Info {
69            name: info.name,
70            parent: info.parent,
71            kind: info.kind.into(),
72            created_at: Some(info.created_at.into()),
73            updated_at: Some(info.updated_at.into()),
74            labels: info.labels,
75        }
76    }
77}
78
79#[derive(Debug, Error)]
80pub enum Error {
81    #[error("Failed to convert GRPC timestamp: {0}")]
82    Timestamp(#[from] prost_types::TimestampError),
83
84    #[error("Invalid enum value: {0}")]
85    InvalidEnumValue(i32),
86}
87
88impl From<Error> for tonic::Status {
89    fn from(err: Error) -> Self {
90        Status::internal(format!("{}", err))
91    }
92}