Skip to content

Commit

Permalink
🐅 conn, socks5: simplify unsafe conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
database64128 committed Jun 20, 2023
1 parent 993e3e5 commit 1ca861e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 17 deletions.
26 changes: 11 additions & 15 deletions conn/addr.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,7 @@ const (
type netipAddrHeader struct {
hi uint64
lo uint64
z unsafe.Pointer
}

type stringHeader struct {
data unsafe.Pointer
len int
z *byte
}

// Addr is the base address type used throughout the package.
Expand All @@ -52,11 +47,8 @@ func (a Addr) ipPort() netip.AddrPort {
return *(*netip.AddrPort)(unsafe.Pointer(&a))
}

func (a Addr) domain() (domain string) {
dp := (*stringHeader)(unsafe.Pointer(&domain))
dp.data = a.addr.z
dp.len = *(*int)(unsafe.Pointer(&a))
return
func (a Addr) domain() string {
return unsafe.String(a.addr.z, a.addr.hi)
}

// Equals returns whether two addresses are the same.
Expand Down Expand Up @@ -249,10 +241,14 @@ func AddrFromDomainPort(domain string, port uint16) (Addr, error) {
if len(domain) == 0 || len(domain) > 255 {
return Addr{}, fmt.Errorf("length of domain %s out of range [1, 255]", domain)
}
dp := (*stringHeader)(unsafe.Pointer(&domain))
addr := Addr{addr: netipAddrHeader{z: dp.data}, port: port, af: addressFamilyDomain}
*(*int)(unsafe.Pointer(&addr)) = dp.len
return addr, nil
return Addr{
addr: netipAddrHeader{
hi: uint64(len(domain)),
z: unsafe.StringData(domain),
},
port: port,
af: addressFamilyDomain,
}, nil
}

// MustAddrFromDomainPort calls [AddrFromDomainPort] and panics on error.
Expand Down
3 changes: 1 addition & 2 deletions socks5/addr.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,7 @@ func ConnAddrFromReader(r io.Reader) (conn.Addr, error) {
if err != nil {
return conn.Addr{}, err
}
b2 := b1[:b[1]:b[1]]
domain := *(*string)(unsafe.Pointer(&b2))
domain := unsafe.String(unsafe.SliceData(b1), b[1])
port := binary.BigEndian.Uint16(b1[b[1]:])
return conn.AddrFromDomainPort(domain, port)

Expand Down

0 comments on commit 1ca861e

Please sign in to comment.