Skip to content

Commit

Permalink
Add a benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Feb 6, 2025
1 parent be1c5ad commit 2a8b8af
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions x/meg/bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package meg_test

import (
"testing"

"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multiaddr/x/meg"
)

type preallocatedCapture struct {
certHashes []string
matcher *meg.MatchState
}

func preallocateCapture() *preallocatedCapture {
p := &preallocatedCapture{}
p.matcher = meg.PatternToMatchState(
meg.Or(
meg.Val(multiaddr.P_IP4),
meg.Val(multiaddr.P_IP6),
meg.Val(multiaddr.P_DNS),
),
meg.Val(multiaddr.P_UDP),
meg.Val(multiaddr.P_WEBRTC_DIRECT),
meg.CaptureZeroOrMore(multiaddr.P_CERTHASH, &p.certHashes),
)
return p
}

var matcher = preallocateCapture()

func (p *preallocatedCapture) IsWebRTCDirectMultiaddr(addr multiaddr.Multiaddr) (bool, int) {
found, _ := meg.Match(p.matcher, addr)
return found, len(p.certHashes)
}

// IsWebRTCDirectMultiaddr returns whether addr is a /webrtc-direct multiaddr with the count of certhashes
// in addr
func IsWebRTCDirectMultiaddr(addr multiaddr.Multiaddr) (bool, int) {
return matcher.IsWebRTCDirectMultiaddr(addr)
}

// IsWebRTCDirectMultiaddrLoop returns whether addr is a /webrtc-direct multiaddr with the count of certhashes
// in addr
func IsWebRTCDirectMultiaddrLoop(addr multiaddr.Multiaddr) (bool, int) {
protos := [...]int{multiaddr.P_IP4, multiaddr.P_IP6, multiaddr.P_DNS, multiaddr.P_UDP, multiaddr.P_WEBRTC_DIRECT}
matchProtos := [...][]int{protos[:3], {protos[3]}, {protos[4]}}
certHashCount := 0
for i, c := range addr {
if i >= len(matchProtos) {
if c.Code() == multiaddr.P_CERTHASH {
certHashCount++
} else {
return false, 0
}
} else {
found := false
for _, proto := range matchProtos[i] {
if c.Code() == proto {
found = true
break
}
}
if !found {
return false, 0
}
}
}
return true, certHashCount
}

func BenchmarkIsWebRTCDirectMultiaddr(b *testing.B) {
addr := multiaddr.StringCast("/ip4/1.2.3.4/udp/1234/webrtc-direct/")

b.ResetTimer()
for i := 0; i < b.N; i++ {
isWebRTC, count := IsWebRTCDirectMultiaddr(addr)
if !isWebRTC || count != 0 {
b.Fatal("unexpected result")
}
}
}

func BenchmarkIsWebRTCDirectMultiaddrLoop(b *testing.B) {
addr := multiaddr.StringCast("/ip4/1.2.3.4/udp/1234/webrtc-direct/")

b.ResetTimer()
for i := 0; i < b.N; i++ {
isWebRTC, count := IsWebRTCDirectMultiaddrLoop(addr)
if !isWebRTC || count != 0 {
b.Fatal("unexpected result")
}
}
}

0 comments on commit 2a8b8af

Please sign in to comment.