Files
akvorado/common/helpers/ipv6.go
Vincent Bernat 23518c3e2e
Some checks failed
CI / 🤖 Check dependabot status (push) Has been cancelled
CI / 🐧 Test on Linux (${{ github.ref_type == 'tag' }}, misc) (push) Has been cancelled
CI / 🐧 Test on Linux (coverage) (push) Has been cancelled
CI / 🐧 Test on Linux (regular) (push) Has been cancelled
CI / ❄️ Build on Nix (push) Has been cancelled
CI / 🍏 Build and test on macOS (push) Has been cancelled
CI / 🧪 End-to-end testing (push) Has been cancelled
CI / 🔍 Upload code coverage (push) Has been cancelled
CI / 🔬 Test only Go (push) Has been cancelled
CI / 🔬 Test only JS (${{ needs.dependabot.outputs.package-ecosystem }}, 20) (push) Has been cancelled
CI / 🔬 Test only JS (${{ needs.dependabot.outputs.package-ecosystem }}, 22) (push) Has been cancelled
CI / 🔬 Test only JS (${{ needs.dependabot.outputs.package-ecosystem }}, 24) (push) Has been cancelled
CI / ⚖️ Check licenses (push) Has been cancelled
CI / 🐋 Build Docker images (push) Has been cancelled
CI / 🐋 Tag Docker images (push) Has been cancelled
CI / 🚀 Publish release (push) Has been cancelled
Update Nix dependency hashes / Update dependency hashes (push) Has been cancelled
common/helpers: add a NetIPTo6() function
This should be netip.To6() but it does not exist and it was rejected.
There is a benchmark showing the improvment of such optimisation:

BenchmarkNetIPTo6/safe_v4-12            170152954                7.054 ns/op
BenchmarkNetIPTo6/unsafe_v4-12          764772190                1.553 ns/op

See https://github.com/golang/go/issues/54365.
2025-11-03 21:36:33 +01:00

35 lines
786 B
Go

// SPDX-FileCopyrightText: 2025 Free Mobile
// SPDX-License-Identifier: AGPL-3.0-only
package helpers
import (
"net/netip"
"unsafe"
)
var (
someIPv6 = netip.MustParseAddr("2001:db8::1")
z6noz = *(*uint64)(unsafe.Add(unsafe.Pointer(&someIPv6), 16))
)
// NetIPTo6 maps an IPv4 to an IPv4-mapped IPv6 and returns an IPv6 unmodified.
// This is unsafe, but there is a test to ensure netip.Addr is like we expect.
// Copying a unique.Handle bypass reference count, but z6noz is "static".
//
// This would be trivial to implement inside netip:
//
// func (ip Addr) Unmap() Addr {
// if ip.Is4() {
// ip.z = z6noz
// }
// return ip
// }
func NetIPTo6(ip netip.Addr) netip.Addr {
if ip.Is4() {
p := (*uint64)(unsafe.Add(unsafe.Pointer(&ip), 16))
*p = z6noz
}
return ip
}