github.com/go-chrono/chrono@v0.0.0-20240102183611-532f0d0d7c34/instant.go (about) 1 package chrono 2 3 import "strconv" 4 5 // Instant represents an instantaneous point in time with nanosecond resolution. 6 type Instant struct { 7 v *int64 8 } 9 10 // Now returns the Instant that represents the current point in time. 11 func Now() Instant { 12 now := monotime() 13 return Instant{ 14 v: &now, 15 } 16 } 17 18 // Compare compares i with i2. If i is before i2, it returns -1; 19 // if i is after i2, it returns 1; if they're the same, it returns 0. 20 func (i Instant) Compare(i2 Instant) int { 21 switch { 22 case i.v == nil: 23 panic("i is not initialized") 24 case i2.v == nil: 25 panic("i2 is not initialized") 26 case *i.v < *i2.v: 27 return -1 28 case *i.v > *i2.v: 29 return 1 30 default: 31 return 0 32 } 33 } 34 35 // Elapsed is shorthand for i.Until(chrono.Now()). 36 func (i Instant) Elapsed() Duration { 37 return i.Until(Now()) 38 } 39 40 func (i Instant) String() string { 41 return strconv.FormatInt(*i.v, 10) 42 } 43 44 // Until returns the Duration that represents the elapsed time from i to v. 45 func (i Instant) Until(i2 Instant) Duration { 46 switch { 47 case i.v == nil: 48 panic("i is not initialized") 49 case i2.v == nil: 50 panic("i2 is not initialized") 51 } 52 53 iv, vv := *i.v, *i2.v 54 if vv < iv { 55 panic("v is smaller than i") 56 } 57 58 d := vv - iv 59 return DurationOf(Extent(d)) 60 } 61 62 // instant is used by the chronotest package. 63 func instant(t int64) Instant { 64 return Instant{ 65 v: &t, 66 } 67 }