encode.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 Yunion
  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 encode
  15. import (
  16. "strings"
  17. )
  18. const lowerhex = "0123456789abcdef"
  19. func ishex(c rune) bool {
  20. switch {
  21. case rune('0') <= c && c <= rune('9'):
  22. return true
  23. case rune('a') <= c && c <= rune('f'):
  24. return true
  25. }
  26. return false
  27. }
  28. func unhex(c rune) byte {
  29. switch {
  30. case rune('0') <= c && c <= rune('9'):
  31. return byte(c) - '0'
  32. case rune('a') <= c && c <= rune('f'):
  33. return byte(c) - 'a' + 10
  34. }
  35. return 0
  36. }
  37. func shouldEncode(c rune) bool {
  38. if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c > 256 {
  39. return false
  40. }
  41. return true
  42. }
  43. func EncodeGoogleLabel(label string) string {
  44. var t strings.Builder
  45. for _, c := range label {
  46. if shouldEncode(c) {
  47. t.WriteByte('_')
  48. t.WriteByte(lowerhex[c>>4])
  49. t.WriteByte(lowerhex[c&15])
  50. continue
  51. }
  52. t.WriteRune(c)
  53. }
  54. return t.String()
  55. }
  56. func DecodeGoogleLable(label string) string {
  57. s := []rune{}
  58. for _, c := range label {
  59. s = append(s, c)
  60. }
  61. var t strings.Builder
  62. for j := 0; j < len(s); {
  63. c := s[j]
  64. if c == rune('_') && j+2 <= len(s) && ishex(s[j+1]) && ishex(s[j+2]) {
  65. t.WriteByte(unhex(s[j+1])<<4 | unhex(s[j+2]))
  66. j += 3
  67. } else {
  68. t.WriteRune(s[j])
  69. j += 1
  70. }
  71. }
  72. return t.String()
  73. }