github.com/mailru/activerecord@v1.12.2/pkg/iproto/util/time/time.go (about) 1 // Package time contains tools for time manipulation. 2 package time 3 4 import "time" 5 6 const ( 7 minDuration time.Duration = -1 << 63 8 maxDuration time.Duration = 1<<63 - 1 9 ) 10 11 type timestamp struct { 12 // sec gives the number of seconds elapsed since some time point 13 // regarding the type of timestamp. 14 sec int64 15 16 // nsec specifies a non-negative nanosecond offset within the seconds. 17 // It must be in the range [0, 999999999]. 18 nsec int32 19 } 20 21 // add returns the timestamp t+d. 22 func (t timestamp) add(d time.Duration) timestamp { 23 t.sec += int64(d / 1e9) 24 25 nsec := t.nsec + int32(d%1e9) 26 if nsec >= 1e9 { 27 t.sec++ 28 29 nsec -= 1e9 30 } else if nsec < 0 { 31 t.sec-- 32 33 nsec += 1e9 34 } 35 36 t.nsec = nsec 37 38 return t 39 } 40 41 // sub return duration t-u. 42 func (t timestamp) sub(u timestamp) time.Duration { 43 d := time.Duration(t.sec-u.sec)*time.Second + time.Duration(int32(t.nsec)-int32(u.nsec)) 44 // Check for overflow or underflow. 45 switch { 46 case u.add(d).equal(t): 47 return d // d is correct 48 case t.before(u): 49 return minDuration // t - u is negative out of range 50 default: 51 return maxDuration // t - u is positive out of range 52 } 53 } 54 55 // equal reports whether the t is equal to u. 56 func (t timestamp) equal(u timestamp) bool { 57 return t.sec == u.sec && t.nsec == u.nsec 58 } 59 60 // equal reports whether the t is before u. 61 func (t timestamp) before(u timestamp) bool { 62 return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec 63 } 64 65 // after reports whether the t is after u. 66 func (t timestamp) after(u timestamp) bool { 67 return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec 68 }