path.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package objabi
  5. import "strings"
  6. // PathToPrefix converts raw string to the prefix that will be used in the
  7. // symbol table. All control characters, space, '%' and '"', as well as
  8. // non-7-bit clean bytes turn into %xx. The period needs escaping only in the
  9. // last segment of the path, and it makes for happier users if we escape that as
  10. // little as possible.
  11. func PathToPrefix(s string) string {
  12. slash := strings.LastIndex(s, "/")
  13. // check for chars that need escaping
  14. n := 0
  15. for r := 0; r < len(s); r++ {
  16. if c := s[r]; c <= ' ' || (c == '.' && r > slash) || c == '%' || c == '"' || c >= 0x7F {
  17. n++
  18. }
  19. }
  20. // quick exit
  21. if n == 0 {
  22. return s
  23. }
  24. // escape
  25. const hex = "0123456789abcdef"
  26. p := make([]byte, 0, len(s)+2*n)
  27. for r := 0; r < len(s); r++ {
  28. if c := s[r]; c <= ' ' || (c == '.' && r > slash) || c == '%' || c == '"' || c >= 0x7F {
  29. p = append(p, '%', hex[c>>4], hex[c&0xF])
  30. } else {
  31. p = append(p, c)
  32. }
  33. }
  34. return string(p)
  35. }