gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/id/id.go (about) 1 package id 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 sliceUnsafe "gitee.com/sy_183/go-common/slice/unsafe" 7 stringUnsafe "gitee.com/sy_183/go-common/strings/unsafe" 8 "net" 9 "sync/atomic" 10 "unsafe" 11 ) 12 13 const ptrSize = 8 14 15 func getTypeId(i interface{}) uintptr { 16 return *(*uintptr)(unsafe.Pointer(&i)) 17 } 18 19 func getTypeIdString(i interface{}) string { 20 bs := make([]byte, 8) 21 binary.BigEndian.PutUint64(bs, uint64(getTypeId(i))) 22 return sliceUnsafe.String(bs) 23 } 24 25 func getIpId(ip net.IP) []byte { 26 ipv4 := ip.To4() 27 if ipv4 == nil { 28 return ip 29 } 30 return ipv4 31 } 32 33 func GenerateIpAddrId(addr *net.IPAddr) string { 34 return sliceUnsafe.String(bytes.Join([][]byte{getIpId(addr.IP), stringUnsafe.Bytes(addr.Zone)}, nil)) 35 } 36 37 func GenerateIpNetId(ipNet *net.IPNet) string { 38 return sliceUnsafe.String(bytes.Join([][]byte{getIpId(ipNet.IP), ipNet.Mask}, nil)) 39 } 40 41 func GenerateTcpAddrId(addr *net.TCPAddr) string { 42 return sliceUnsafe.String(bytes.Join([][]byte{ 43 getIpId(addr.IP), 44 {byte(addr.Port >> 8), byte(addr.Port)}, 45 stringUnsafe.Bytes(addr.Zone), 46 }, nil)) 47 } 48 49 func GenerateUdpAddrId(addr *net.UDPAddr) string { 50 return GenerateTcpAddrId((*net.TCPAddr)(addr)) 51 } 52 53 func GenerateUnixAddrId(addr *net.UnixAddr) string { 54 return addr.Net + ":" + addr.Name 55 } 56 57 func GeneratePairTcpAddrId(localAddr, remoteAddr *net.TCPAddr) string { 58 return GenerateTcpAddrId(localAddr) + GenerateTcpAddrId(remoteAddr) 59 } 60 61 func GeneratePairUdpAddrId(localAddr, remoteAddr *net.UDPAddr) string { 62 return GenerateUdpAddrId(localAddr) + GenerateUdpAddrId(remoteAddr) 63 } 64 65 func GenerateTcpConnId(conn *net.TCPConn) string { 66 return GeneratePairTcpAddrId(conn.LocalAddr().(*net.TCPAddr), conn.RemoteAddr().(*net.TCPAddr)) 67 } 68 69 func GenerateUdpConnId(conn *net.UDPConn) string { 70 return GeneratePairUdpAddrId(conn.LocalAddr().(*net.UDPAddr), conn.RemoteAddr().(*net.UDPAddr)) 71 } 72 73 var ( 74 ipAddrTypeId = getTypeIdString(&net.IPAddr{}) 75 ipNetTypeId = getTypeIdString(&net.IPAddr{}) 76 tcpAddrTypeId = getTypeIdString(&net.TCPAddr{}) 77 udpAddrTypeId = getTypeIdString(&net.UDPAddr{}) 78 unixAddrId = getTypeIdString(&net.UnixAddr{}) 79 ) 80 81 func GenerateAddrId(addr net.Addr) string { 82 switch rawAddr := addr.(type) { 83 case *net.IPAddr: 84 return ipAddrTypeId + GenerateIpAddrId(rawAddr) 85 case *net.IPNet: 86 return ipNetTypeId + GenerateIpNetId(rawAddr) 87 case *net.TCPAddr: 88 return tcpAddrTypeId + GenerateTcpAddrId(rawAddr) 89 case *net.UDPAddr: 90 return udpAddrTypeId + GenerateUdpAddrId(rawAddr) 91 case *net.UnixAddr: 92 return unixAddrId + GenerateUnixAddrId(rawAddr) 93 default: 94 return getTypeIdString(addr) + addr.String() 95 } 96 } 97 98 func Uint64Id(context *uint64) uint64 { 99 return atomic.AddUint64(context, 1) 100 }