@@ -56,7 +56,7 @@ impl Sonyflake {
5656 pub fn next_id ( & self ) -> Result < u64 , Error > {
5757 let mut internals = self . 0 . internals . lock ( ) . map_err ( |_| Error :: MutexPoisoned ) ?;
5858
59- let current = current_elapsed_time ( self . 0 . start_time ) ;
59+ let current = current_elapsed_time ( self . 0 . start_time ) ? ;
6060 if internals. elapsed_time < current {
6161 internals. elapsed_time = current;
6262 internals. sequence = 0 ;
@@ -66,7 +66,7 @@ impl Sonyflake {
6666 if internals. sequence == 0 {
6767 internals. elapsed_time += 1 ;
6868 let overtime = internals. elapsed_time - current;
69- thread:: sleep ( sleep_time ( overtime) ) ;
69+ thread:: sleep ( sleep_time ( overtime) ? ) ;
7070 }
7171 }
7272
@@ -91,17 +91,25 @@ impl Clone for Sonyflake {
9191
9292const SONYFLAKE_TIME_UNIT : i64 = 10_000_000 ; // nanoseconds, i.e. 10msec
9393
94- pub ( crate ) fn to_sonyflake_time ( time : DateTime < Utc > ) -> i64 {
95- time. timestamp_nanos ( ) / SONYFLAKE_TIME_UNIT
94+ pub ( crate ) fn to_sonyflake_time ( time : DateTime < Utc > ) -> Result < i64 , Error > {
95+ Ok ( time
96+ . timestamp_nanos_opt ( )
97+ . ok_or ( Error :: FailedToGetCurrentTime ) ?
98+ / SONYFLAKE_TIME_UNIT )
9699}
97100
98- fn current_elapsed_time ( start_time : i64 ) -> i64 {
99- to_sonyflake_time ( Utc :: now ( ) ) - start_time
101+ fn current_elapsed_time ( start_time : i64 ) -> Result < i64 , Error > {
102+ Ok ( to_sonyflake_time ( Utc :: now ( ) ) ? - start_time)
100103}
101104
102- fn sleep_time ( overtime : i64 ) -> Duration {
103- Duration :: from_millis ( overtime as u64 * 10 )
104- - Duration :: from_nanos ( ( Utc :: now ( ) . timestamp_nanos ( ) % SONYFLAKE_TIME_UNIT ) as u64 )
105+ fn sleep_time ( overtime : i64 ) -> Result < Duration , Error > {
106+ Ok ( Duration :: from_millis ( overtime as u64 * 10 )
107+ - Duration :: from_nanos (
108+ ( Utc :: now ( )
109+ . timestamp_nanos_opt ( )
110+ . ok_or ( Error :: FailedToGetCurrentTime ) ?
111+ % SONYFLAKE_TIME_UNIT ) as u64 ,
112+ ) )
105113}
106114
107115pub struct DecomposedSonyflake {
0 commit comments