utils.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "encoding/binary"
  17. "errors"
  18. "net"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. var (
  24. // ErrEmptyIP an error for empty ip strings
  25. ErrEmptyIP = errors.New("empty string given for ip")
  26. // ErrNotHostColonPort an error for invalid host port string
  27. ErrNotHostColonPort = errors.New("expecting host:port")
  28. // ErrNotFourOctets an error for the wrong number of octets after splitting a string
  29. ErrNotFourOctets = errors.New("Wrong number of octets")
  30. )
  31. // ParseIPToUint32 converts a string ip (e.g. "x.y.z.w") to an uint32
  32. func ParseIPToUint32(ip string) (uint32, error) {
  33. if ip == "" {
  34. return 0, ErrEmptyIP
  35. }
  36. if ip == "localhost" {
  37. return 127<<24 | 1, nil
  38. }
  39. octets := strings.Split(ip, ".")
  40. if len(octets) != 4 {
  41. return 0, ErrNotFourOctets
  42. }
  43. var intIP uint32
  44. for i := 0; i < 4; i++ {
  45. octet, err := strconv.Atoi(octets[i])
  46. if err != nil {
  47. return 0, err
  48. }
  49. intIP = (intIP << 8) | uint32(octet)
  50. }
  51. return intIP, nil
  52. }
  53. // ParsePort converts port number from string to uin16
  54. func ParsePort(portString string) (uint16, error) {
  55. port, err := strconv.ParseUint(portString, 10, 16)
  56. return uint16(port), err
  57. }
  58. // PackIPAsUint32 packs an IPv4 as uint32
  59. func PackIPAsUint32(ip net.IP) uint32 {
  60. if ipv4 := ip.To4(); ipv4 != nil {
  61. return binary.BigEndian.Uint32(ipv4)
  62. }
  63. return 0
  64. }
  65. // TimeToMicrosecondsSinceEpochInt64 converts Go time.Time to a long
  66. // representing time since epoch in microseconds, which is used expected
  67. // in the Jaeger spans encoded as Thrift.
  68. func TimeToMicrosecondsSinceEpochInt64(t time.Time) int64 {
  69. // ^^^ Passing time.Time by value is faster than passing a pointer!
  70. // BenchmarkTimeByValue-8 2000000000 1.37 ns/op
  71. // BenchmarkTimeByPtr-8 2000000000 1.98 ns/op
  72. return t.UnixNano() / 1000
  73. }