Skip to content

Commit

Permalink
reduce heap allocations in protocol (#361)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #361

Optimize few conversions using bit shifts.

Reviewed By: leoleovich

Differential Revision: D58408274

fbshipit-source-id: 34af37f0f8d1a25bb22f93cd184f0511bee5f843
  • Loading branch information
abulimov authored and facebook-github-bot committed Jun 11, 2024
1 parent 7940a9b commit fa7eed6
Showing 1 changed file with 22 additions and 18 deletions.
40 changes: 22 additions & 18 deletions ptp/protocol/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,15 +199,13 @@ func (c ClockIdentity) String() string {

// MAC turns ClockIdentity into the MAC address it was based upon. EUI-48 is assumed.
func (c ClockIdentity) MAC() net.HardwareAddr {
asBytes := [8]byte{}
binary.BigEndian.PutUint64(asBytes[:], uint64(c))
mac := make(net.HardwareAddr, 6)
mac[0] = asBytes[0]
mac[1] = asBytes[1]
mac[2] = asBytes[2]
mac[3] = asBytes[5]
mac[4] = asBytes[6]
mac[5] = asBytes[7]
mac[0] = byte(c >> 56)
mac[1] = byte(c >> 48)
mac[2] = byte(c >> 40)
mac[3] = byte(c >> 16)
mac[4] = byte(c >> 8)
mac[5] = byte(c)
return mac
}

Expand Down Expand Up @@ -279,8 +277,8 @@ func (s PTPSeconds) Empty() bool {

// Seconds returns number of seconds as uint64
func (s PTPSeconds) Seconds() uint64 {
b := append([]byte{0x0, 0x0}, s[:]...)
return binary.BigEndian.Uint64(b)
return uint64(s[5]) | uint64(s[4])<<8 | uint64(s[3])<<16 | uint64(s[2])<<24 |
uint64(s[1])<<32 | uint64(s[0])<<40
}

// Time returns number of seconds in as Time
Expand All @@ -304,11 +302,14 @@ func NewPTPSeconds(t time.Time) PTPSeconds {
if t.IsZero() {
return PTPSeconds{}
}
b := [8]byte{}
v := uint64(t.Unix())
s := PTPSeconds{}
binary.BigEndian.PutUint64(b[:], uint64(t.Unix()))
// take last 6 bytes from 8 bytes of int64
copy(s[:], b[2:])
s[0] = byte(v >> 40)
s[1] = byte(v >> 32)
s[2] = byte(v >> 24)
s[3] = byte(v >> 16)
s[4] = byte(v >> 8)
s[5] = byte(v)
return s
}

Expand Down Expand Up @@ -354,10 +355,13 @@ func NewTimestamp(t time.Time) Timestamp {
ts := Timestamp{
Nanoseconds: uint32(t.Nanosecond()),
}
b := [8]byte{}
binary.BigEndian.PutUint64(b[:], uint64(t.Unix()))
// take last 6 bytes from 8 bytes of int64
copy(ts.Seconds[:], b[2:])
v := uint64(t.Unix())
ts.Seconds[0] = byte(v >> 40)
ts.Seconds[1] = byte(v >> 32)
ts.Seconds[2] = byte(v >> 24)
ts.Seconds[3] = byte(v >> 16)
ts.Seconds[4] = byte(v >> 8)
ts.Seconds[5] = byte(v)
return ts
}

Expand Down

0 comments on commit fa7eed6

Please sign in to comment.