time.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2018 The GoPacket Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package gopacket
  7. import (
  8. "fmt"
  9. "math"
  10. "time"
  11. )
  12. // TimestampResolution represents the resolution of timestamps in Base^Exponent.
  13. type TimestampResolution struct {
  14. Base, Exponent int
  15. }
  16. func (t TimestampResolution) String() string {
  17. return fmt.Sprintf("%d^%d", t.Base, t.Exponent)
  18. }
  19. // ToDuration returns the smallest representable time difference as a time.Duration
  20. func (t TimestampResolution) ToDuration() time.Duration {
  21. if t.Base == 0 {
  22. return 0
  23. }
  24. if t.Exponent == 0 {
  25. return time.Second
  26. }
  27. switch t.Base {
  28. case 10:
  29. return time.Duration(math.Pow10(t.Exponent + 9))
  30. case 2:
  31. if t.Exponent < 0 {
  32. return time.Second >> uint(-t.Exponent)
  33. }
  34. return time.Second << uint(t.Exponent)
  35. default:
  36. // this might loose precision
  37. return time.Duration(float64(time.Second) * math.Pow(float64(t.Base), float64(t.Exponent)))
  38. }
  39. }
  40. // TimestampResolutionInvalid represents an invalid timestamp resolution
  41. var TimestampResolutionInvalid = TimestampResolution{}
  42. // TimestampResolutionMillisecond is a resolution of 10^-3s
  43. var TimestampResolutionMillisecond = TimestampResolution{10, -3}
  44. // TimestampResolutionMicrosecond is a resolution of 10^-6s
  45. var TimestampResolutionMicrosecond = TimestampResolution{10, -6}
  46. // TimestampResolutionNanosecond is a resolution of 10^-9s
  47. var TimestampResolutionNanosecond = TimestampResolution{10, -9}
  48. // TimestampResolutionNTP is the resolution of NTP timestamps which is 2^-32 ≈ 233 picoseconds
  49. var TimestampResolutionNTP = TimestampResolution{2, -32}
  50. // TimestampResolutionCaptureInfo is the resolution used in CaptureInfo, which his currently nanosecond
  51. var TimestampResolutionCaptureInfo = TimestampResolutionNanosecond
  52. // PacketSourceResolution is an interface for packet data sources that
  53. // support reporting the timestamp resolution of the aqcuired timestamps.
  54. // Returned timestamps will always have NanosecondTimestampResolution due
  55. // to the use of time.Time, but scaling might have occured if acquired
  56. // timestamps have a different resolution.
  57. type PacketSourceResolution interface {
  58. // Resolution returns the timestamp resolution of acquired timestamps before scaling to NanosecondTimestampResolution.
  59. Resolution() TimestampResolution
  60. }