Skip to content

Instantly share code, notes, and snippets.

@vyamkovyi
Last active April 2, 2024 20:57
Show Gist options
  • Save vyamkovyi/55b68d2d5d6375a3cb5de7f943e59d78 to your computer and use it in GitHub Desktop.
Save vyamkovyi/55b68d2d5d6375a3cb5de7f943e59d78 to your computer and use it in GitHub Desktop.
Geogarbage
// WGS84 EPSG identifier
const WGS84 = 4326
const DEG_TO_RAD = math.Pi / 180.0
const RAD_TO_DEG = 180.0 / math.Pi
// DecodeUTF16 converts a UTF-16 string to a UTF-8 string.
func DecodeUTF16(b []byte) (string, error) {
if len(b)%2 != 0 {
return "", errors.New("must have even length byte slice")
}
u16s := make([]uint16, 1)
ret := &bytes.Buffer{}
b8buf := make([]byte, 4)
lb := len(b)
for i := 0; i < lb; i+=2 {
u16s[0] = uint16(b[i]) + (uint16(b[i+1]) << 8)
r := utf16.Decode(u16s)
n := utf8.EncodeRune(b8buf, r[0])
ret.Write(b8buf[:n])
}
return ret.String(), nil
}
// DmToSd converts degrees/minutes formatted WGS84 coordinate to it's
// actual value in degrees.
func DmToSd(coord string) (float64, error) {
if coord == "0" {
return 0, nil
}
rg, err := regexp.Compile(`^(\d+)(\d\d\.\d+)$`)
if err != nil {
return 0, err
}
matches := rg.FindStringSubmatch(coord)
d, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
return 0, err
}
m, err := strconv.ParseFloat(matches[2], 64)
return d + m/60, err
}
// Near checks a and b difference against required precision.
func Near(a, b, precision float64) bool {
return math.Abs(a-b) <= precision
}
func IpToInt(ip net.IP) uint32 {
if len(ip) == 16 {
return binary.BigEndian.Uint32(ip[12:16])
}
return binary.BigEndian.Uint32(ip)
}
func IntToIp(nn uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, nn)
return ip
}
// IsLocal checks if addr is a local address on any of network interfaces
// available in system. If any error occurs, assumes that the address is
// local (returns true, err).
func IsLocal(addr net.Addr) (bool, error) {
var ifaces []net.Interface
var addrs []net.Addr
ifaces, err := net.Interfaces()
if err != nil {
return true, err
}
for _, iface := range ifaces {
addrs, err = iface.Addrs()
if err != nil {
return true, err
}
var isLocal bool
for _, lAddr := range addrs {
if lAddr == addr {
isLocal = true
break
}
}
if isLocal {
return true, nil
}
}
return false, nil
}
// pure magic
func randFileName(prefix string) string {
return prefix + strconv.Itoa(int(1e9 + (uint32(time.Now().UnixNano() + int64(os.Getpid())) * 1664525 + 1013904223) % 1e9))[1:]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment