You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timestruct.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. package unix
  6. import "time"
  7. // TimespecToNsec returns the time stored in ts as nanoseconds.
  8. func TimespecToNsec(ts Timespec) int64 { return ts.Nano() }
  9. // NsecToTimespec converts a number of nanoseconds into a Timespec.
  10. func NsecToTimespec(nsec int64) Timespec {
  11. sec := nsec / 1e9
  12. nsec = nsec % 1e9
  13. if nsec < 0 {
  14. nsec += 1e9
  15. sec--
  16. }
  17. return setTimespec(sec, nsec)
  18. }
  19. // TimeToTimespec converts t into a Timespec.
  20. // On some 32-bit systems the range of valid Timespec values are smaller
  21. // than that of time.Time values. So if t is out of the valid range of
  22. // Timespec, it returns a zero Timespec and ERANGE.
  23. func TimeToTimespec(t time.Time) (Timespec, error) {
  24. sec := t.Unix()
  25. nsec := int64(t.Nanosecond())
  26. ts := setTimespec(sec, nsec)
  27. // Currently all targets have either int32 or int64 for Timespec.Sec.
  28. // If there were a new target with floating point type for it, we have
  29. // to consider the rounding error.
  30. if int64(ts.Sec) != sec {
  31. return Timespec{}, ERANGE
  32. }
  33. return ts, nil
  34. }
  35. // TimevalToNsec returns the time stored in tv as nanoseconds.
  36. func TimevalToNsec(tv Timeval) int64 { return tv.Nano() }
  37. // NsecToTimeval converts a number of nanoseconds into a Timeval.
  38. func NsecToTimeval(nsec int64) Timeval {
  39. nsec += 999 // round up to microsecond
  40. usec := nsec % 1e9 / 1e3
  41. sec := nsec / 1e9
  42. if usec < 0 {
  43. usec += 1e6
  44. sec--
  45. }
  46. return setTimeval(sec, usec)
  47. }
  48. // Unix returns the time stored in ts as seconds plus nanoseconds.
  49. func (ts *Timespec) Unix() (sec int64, nsec int64) {
  50. return int64(ts.Sec), int64(ts.Nsec)
  51. }
  52. // Unix returns the time stored in tv as seconds plus nanoseconds.
  53. func (tv *Timeval) Unix() (sec int64, nsec int64) {
  54. return int64(tv.Sec), int64(tv.Usec) * 1000
  55. }
  56. // Nano returns the time stored in ts as nanoseconds.
  57. func (ts *Timespec) Nano() int64 {
  58. return int64(ts.Sec)*1e9 + int64(ts.Nsec)
  59. }
  60. // Nano returns the time stored in tv as nanoseconds.
  61. func (tv *Timeval) Nano() int64 {
  62. return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
  63. }