github.com/chnsz/golangsdk@v0.0.0-20240506093406-85a3fbfa605b/auth/core/signer/escape.go (about)

     1  package signer
     2  
     3  func shouldEscape(c byte) bool {
     4  	if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c == '-' || c == '~' || c == '.' {
     5  		return false
     6  	}
     7  	return true
     8  }
     9  
    10  func escape(s string) string {
    11  	hexCount := 0
    12  	for i := 0; i < len(s); i++ {
    13  		c := s[i]
    14  		if shouldEscape(c) {
    15  			hexCount++
    16  		}
    17  	}
    18  
    19  	if hexCount == 0 {
    20  		return s
    21  	}
    22  
    23  	t := make([]byte, len(s)+2*hexCount)
    24  	j := 0
    25  	for i := 0; i < len(s); i++ {
    26  		switch c := s[i]; {
    27  		case shouldEscape(c):
    28  			t[j] = '%'
    29  			t[j+1] = "0123456789ABCDEF"[c>>4]
    30  			t[j+2] = "0123456789ABCDEF"[c&15]
    31  			j += 3
    32  		default:
    33  			t[j] = s[i]
    34  			j++
    35  		}
    36  	}
    37  	return string(t)
    38  }