1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#![doc(html_root_url = "https://docs.rs/prost-types/0.6.1")]
use std::convert::TryFrom;
use std::i32;
use std::i64;
use std::time;
include!("protobuf.rs");
pub mod compiler {
include!("compiler.rs");
}
const NANOS_PER_SECOND: i32 = 1_000_000_000;
impl Duration {
fn normalize(&mut self) {
if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
self.seconds += (self.nanos / NANOS_PER_SECOND) as i64;
self.nanos %= NANOS_PER_SECOND;
}
if self.seconds < 0 && self.nanos > 0 {
self.seconds += 1;
self.nanos -= NANOS_PER_SECOND;
} else if self.seconds > 0 && self.nanos < 0 {
self.seconds -= 1;
self.nanos += NANOS_PER_SECOND;
}
}
}
impl From<time::Duration> for Duration {
fn from(duration: time::Duration) -> Duration {
let seconds = duration.as_secs();
let seconds = if seconds > i64::MAX as u64 {
i64::MAX
} else {
seconds as i64
};
let nanos = duration.subsec_nanos();
let nanos = if nanos > i32::MAX as u32 {
i32::MAX
} else {
nanos as i32
};
let mut duration = Duration { seconds, nanos };
duration.normalize();
duration
}
}
impl TryFrom<Duration> for time::Duration {
type Error = time::Duration;
fn try_from(mut duration: Duration) -> Result<time::Duration, time::Duration> {
duration.normalize();
if duration.seconds >= 0 {
Ok(time::Duration::new(
duration.seconds as u64,
duration.nanos as u32,
))
} else {
Err(time::Duration::new(
(-duration.seconds) as u64,
(-duration.nanos) as u32,
))
}
}
}
impl Timestamp {
fn normalize(&mut self) {
if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
self.seconds += (self.nanos / NANOS_PER_SECOND) as i64;
self.nanos %= NANOS_PER_SECOND;
}
if self.nanos < 0 {
self.seconds -= 1;
self.nanos += NANOS_PER_SECOND;
}
}
}
impl From<time::SystemTime> for Timestamp {
fn from(time: time::SystemTime) -> Timestamp {
let duration = Duration::from(time.duration_since(time::UNIX_EPOCH).unwrap());
Timestamp {
seconds: duration.seconds,
nanos: duration.nanos,
}
}
}
impl TryFrom<Timestamp> for time::SystemTime {
type Error = time::Duration;
fn try_from(mut timestamp: Timestamp) -> Result<time::SystemTime, time::Duration> {
timestamp.normalize();
if timestamp.seconds >= 0 {
Ok(time::UNIX_EPOCH
+ time::Duration::new(timestamp.seconds as u64, timestamp.nanos as u32))
} else {
let mut duration = Duration {
seconds: -timestamp.seconds,
nanos: timestamp.nanos,
};
duration.normalize();
Err(time::Duration::new(
duration.seconds as u64,
duration.nanos as u32,
))
}
}
}