blob: 6d116cdfbc72af8e9fe361a13878c430b5ba5fe6 [file] [log] [blame]
Takahiro Suzukid7bf8202020-12-17 20:21:59 +09001// 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
7package gopacket
8
9import (
10 "fmt"
11 "math"
12 "time"
13)
14
15// TimestampResolution represents the resolution of timestamps in Base^Exponent.
16type TimestampResolution struct {
17 Base, Exponent int
18}
19
20func (t TimestampResolution) String() string {
21 return fmt.Sprintf("%d^%d", t.Base, t.Exponent)
22}
23
24// ToDuration returns the smallest representable time difference as a time.Duration
25func (t TimestampResolution) ToDuration() time.Duration {
26 if t.Base == 0 {
27 return 0
28 }
29 if t.Exponent == 0 {
30 return time.Second
31 }
32 switch t.Base {
33 case 10:
34 return time.Duration(math.Pow10(t.Exponent + 9))
35 case 2:
36 if t.Exponent < 0 {
37 return time.Second >> uint(-t.Exponent)
38 }
39 return time.Second << uint(t.Exponent)
40 default:
41 // this might loose precision
42 return time.Duration(float64(time.Second) * math.Pow(float64(t.Base), float64(t.Exponent)))
43 }
44}
45
46// TimestampResolutionInvalid represents an invalid timestamp resolution
47var TimestampResolutionInvalid = TimestampResolution{}
48
49// TimestampResolutionMillisecond is a resolution of 10^-3s
50var TimestampResolutionMillisecond = TimestampResolution{10, -3}
51
52// TimestampResolutionMicrosecond is a resolution of 10^-6s
53var TimestampResolutionMicrosecond = TimestampResolution{10, -6}
54
55// TimestampResolutionNanosecond is a resolution of 10^-9s
56var TimestampResolutionNanosecond = TimestampResolution{10, -9}
57
58// TimestampResolutionNTP is the resolution of NTP timestamps which is 2^-32 ≈ 233 picoseconds
59var TimestampResolutionNTP = TimestampResolution{2, -32}
60
61// TimestampResolutionCaptureInfo is the resolution used in CaptureInfo, which his currently nanosecond
62var TimestampResolutionCaptureInfo = TimestampResolutionNanosecond
63
64// PacketSourceResolution is an interface for packet data sources that
65// support reporting the timestamp resolution of the aqcuired timestamps.
66// Returned timestamps will always have NanosecondTimestampResolution due
67// to the use of time.Time, but scaling might have occured if acquired
68// timestamps have a different resolution.
69type PacketSourceResolution interface {
70 // Resolution returns the timestamp resolution of acquired timestamps before scaling to NanosecondTimestampResolution.
71 Resolution() TimestampResolution
72}