timestruct.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
  5. // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
  6. package unix
  7. import "time"
  8. // TimespecToNSec returns the time stored in ts as nanoseconds.
  9. func TimespecToNsec(ts Timespec) int64 { return ts.Nano() }
  10. // NsecToTimespec converts a number of nanoseconds into a Timespec.
  11. func NsecToTimespec(nsec int64) Timespec {
  12. sec := nsec / 1e9
  13. nsec = nsec % 1e9
  14. if nsec < 0 {
  15. nsec += 1e9
  16. sec--
  17. }
  18. return setTimespec(sec, nsec)
  19. }
  20. // TimeToTimespec converts t into a Timespec.
  21. // On some 32-bit systems the range of valid Timespec values are smaller
  22. // than that of time.Time values. So if t is out of the valid range of
  23. // Timespec, it returns a zero Timespec and ERANGE.
  24. func TimeToTimespec(t time.Time) (Timespec, error) {
  25. sec := t.Unix()
  26. nsec := int64(t.Nanosecond())
  27. ts := setTimespec(sec, nsec)
  28. // Currently all targets have either int32 or int64 for Timespec.Sec.
  29. // If there were a new target with floating point type for it, we have
  30. // to consider the rounding error.
  31. if int64(ts.Sec) != sec {
  32. return Timespec{}, ERANGE
  33. }
  34. return ts, nil
  35. }
  36. // TimevalToNsec returns the time stored in tv as nanoseconds.
  37. func TimevalToNsec(tv Timeval) int64 { return tv.Nano() }
  38. // NsecToTimeval converts a number of nanoseconds into a Timeval.
  39. func NsecToTimeval(nsec int64) Timeval {
  40. nsec += 999 // round up to microsecond
  41. usec := nsec % 1e9 / 1e3
  42. sec := nsec / 1e9
  43. if usec < 0 {
  44. usec += 1e6
  45. sec--
  46. }
  47. return setTimeval(sec, usec)
  48. }
  49. // Unix returns the time stored in ts as seconds plus nanoseconds.
  50. func (ts *Timespec) Unix() (sec int64, nsec int64) {
  51. return int64(ts.Sec), int64(ts.Nsec)
  52. }
  53. // Unix returns the time stored in tv as seconds plus nanoseconds.
  54. func (tv *Timeval) Unix() (sec int64, nsec int64) {
  55. return int64(tv.Sec), int64(tv.Usec) * 1000
  56. }
  57. // Nano returns the time stored in ts as nanoseconds.
  58. func (ts *Timespec) Nano() int64 {
  59. return int64(ts.Sec)*1e9 + int64(ts.Nsec)
  60. }
  61. // Nano returns the time stored in tv as nanoseconds.
  62. func (tv *Timeval) Nano() int64 {
  63. return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
  64. }