File tree Expand file tree Collapse file tree 2 files changed +42
-4
lines changed Expand file tree Collapse file tree 2 files changed +42
-4
lines changed Original file line number Diff line number Diff line change @@ -701,18 +701,26 @@ func (ip Addr) As4() (a4 [4]byte) {
701
701
702
702
// AsSlice returns an IPv4 or IPv6 address in its respective 4-byte or 16-byte representation.
703
703
func (ip Addr ) AsSlice () []byte {
704
+ var ret []byte
705
+ if ip .z == z4 {
706
+ ret = make ([]byte , 4 )
707
+ } else {
708
+ ret = make ([]byte , 16 )
709
+ }
710
+ return ip .asSlice (ret )
711
+ }
712
+
713
+ func (ip Addr ) asSlice (ret []byte ) []byte {
704
714
switch ip .z {
705
715
case z0 :
706
716
return nil
707
717
case z4 :
708
- var ret [4 ]byte
709
718
bePutUint32 (ret [:], uint32 (ip .addr .lo ))
710
- return ret [:]
719
+ return ret
711
720
default :
712
- var ret [16 ]byte
713
721
bePutUint64 (ret [:8 ], ip .addr .hi )
714
722
bePutUint64 (ret [8 :], ip .addr .lo )
715
- return ret [:]
723
+ return ret
716
724
}
717
725
}
718
726
Original file line number Diff line number Diff line change @@ -2008,6 +2008,36 @@ func TestAsSlice(t *testing.T) {
2008
2008
}
2009
2009
}
2010
2010
2011
+ func BenchmarkAsSliceAddrv4 (b * testing.B ) {
2012
+ addr := MustParseAddr ("192.0.2.1" )
2013
+ for i := 0 ; i < b .N ; i ++ {
2014
+ addr .AsSlice ()
2015
+ }
2016
+ }
2017
+
2018
+ func BenchmarkAsSliceAddrv6 (b * testing.B ) {
2019
+ addr := MustParseAddr ("2001:db8::1" )
2020
+ for i := 0 ; i < b .N ; i ++ {
2021
+ addr .AsSlice ()
2022
+ }
2023
+ }
2024
+
2025
+ var asSliceOut []byte
2026
+
2027
+ func BenchmarkAsSliceAddrv4Escapes (b * testing.B ) {
2028
+ addr := MustParseAddr ("192.0.2.1" )
2029
+ for i := 0 ; i < b .N ; i ++ {
2030
+ asSliceOut = addr .AsSlice ()
2031
+ }
2032
+ }
2033
+
2034
+ func BenchmarkAsSliceAddrv6Escapes (b * testing.B ) {
2035
+ addr := MustParseAddr ("2001:db8::1" )
2036
+ for i := 0 ; i < b .N ; i ++ {
2037
+ asSliceOut = addr .AsSlice ()
2038
+ }
2039
+ }
2040
+
2011
2041
var sink16 [16 ]byte
2012
2042
2013
2043
func BenchmarkAs16 (b * testing.B ) {
You can’t perform that action at this time.
0 commit comments