Created
March 20, 2025 14:25
-
-
Save millken/838a528ede2c7f7f289f6a7e7197e0f0 to your computer and use it in GitHub Desktop.
fast golang ip2long
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//go:noinline | |
func IpToLong(ipStr string) uint32 { | |
ptr := unsafe.Pointer(unsafe.StringData(ipStr)) | |
var ( | |
n uint32 | |
oct uint32 | |
p = ptr | |
) | |
// 第一段: XXX. | |
for { | |
c := *(*byte)(p) | |
if c == '.' { | |
p = unsafe.Add(p, 1) | |
break | |
} | |
oct = oct*10 + uint32(c&0x0F) // 利用 ASCII 特性省去 -'0' | |
p = unsafe.Add(p, 1) | |
} | |
n = oct << 24 | |
// 第二段: XXX. | |
oct = 0 | |
for { | |
c := *(*byte)(p) | |
if c == '.' { | |
p = unsafe.Add(p, 1) | |
break | |
} | |
oct = oct*10 + uint32(c&0x0F) | |
p = unsafe.Add(p, 1) | |
} | |
n |= oct << 16 | |
// 第三段: XXX. | |
oct = 0 | |
for { | |
c := *(*byte)(p) | |
if c == '.' { | |
p = unsafe.Add(p, 1) | |
break | |
} | |
oct = oct*10 + uint32(c&0x0F) | |
p = unsafe.Add(p, 1) | |
} | |
n |= oct << 8 | |
// 第四段: XXX | |
oct = 0 | |
for uintptr(unsafe.Pointer(p))-uintptr(ptr) < uintptr(len(ipStr)) { | |
c := *(*byte)(p) | |
oct = oct*10 + uint32(c&0x0F) | |
p = unsafe.Add(p, 1) | |
} | |
return n | oct | |
} |
Author
millken
commented
Mar 20, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment