Skip to content

Commit 57a5a04

Browse files
committed
unix: add unix.TimeToPtpClockTime on Linux
Add time conversion helpers for PtpClockTime similar to those existing for Timespec and Timeval.
1 parent 256d1df commit 57a5a04

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

unix/timestruct_linux.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
5+
//go:build linux
6+
7+
package unix
8+
9+
import "time"
10+
11+
// TimeToPtpClockTime returns t as PtpClockTime
12+
func TimeToPtpClockTime(t time.Time) PtpClockTime {
13+
sec := t.Unix()
14+
nsec := uint32(t.Nanosecond())
15+
return PtpClockTime{Sec: sec, Nsec: nsec}
16+
}
17+
18+
// Time returns PTPClockTime as time.Time
19+
func (t *PtpClockTime) Time() time.Time {
20+
return time.Unix(t.Sec, int64(t.Nsec))
21+
}
22+
23+
// Unix returns the time stored in t as seconds plus nanoseconds.
24+
func (t *PtpClockTime) Unix() (sec int64, nsec int64) {
25+
return t.Sec, int64(t.Nsec)
26+
}

unix/timestruct_linux_test.go

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright 2017 The Go Authors. All right reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
//go:build linux
6+
7+
package unix_test
8+
9+
import (
10+
"testing"
11+
"time"
12+
13+
"golang.org/x/sys/unix"
14+
)
15+
16+
func TestTimeToPtpClockTime(t *testing.T) {
17+
testcases := []struct {
18+
time time.Time
19+
}{
20+
{time.Unix(0, 0)},
21+
{time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)},
22+
{time.Date(2262, time.December, 31, 23, 0, 0, 0, time.UTC)},
23+
{time.Unix(0x7FFFFFFF, 0)},
24+
{time.Unix(0x80000000, 0)},
25+
{time.Unix(0x7FFFFFFF, 1000000000)},
26+
{time.Unix(0x7FFFFFFF, 999999999)},
27+
{time.Unix(-0x80000000, 0)},
28+
{time.Unix(-0x80000001, 0)},
29+
{time.Date(2038, time.January, 19, 3, 14, 7, 0, time.UTC)},
30+
{time.Date(2038, time.January, 19, 3, 14, 8, 0, time.UTC)},
31+
{time.Date(1901, time.December, 13, 20, 45, 52, 0, time.UTC)},
32+
{time.Date(1901, time.December, 13, 20, 45, 51, 0, time.UTC)},
33+
}
34+
35+
for _, tc := range testcases {
36+
ts := unix.TimeToPtpClockTime(tc.time)
37+
tstime := time.Unix(int64(ts.Sec), int64(ts.Nsec))
38+
if !tstime.Equal(tc.time) {
39+
t.Errorf("TimeToPtpClockTime(%v) is the time %v", tc.time, tstime)
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)