ascii.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2021 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 http2
  5. import "strings"
  6. // The HTTP protocols are defined in terms of ASCII, not Unicode. This file
  7. // contains helper functions which may use Unicode-aware functions which would
  8. // otherwise be unsafe and could introduce vulnerabilities if used improperly.
  9. // asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
  10. // are equal, ASCII-case-insensitively.
  11. func asciiEqualFold(s, t string) bool {
  12. if len(s) != len(t) {
  13. return false
  14. }
  15. for i := 0; i < len(s); i++ {
  16. if lower(s[i]) != lower(t[i]) {
  17. return false
  18. }
  19. }
  20. return true
  21. }
  22. // lower returns the ASCII lowercase version of b.
  23. func lower(b byte) byte {
  24. if 'A' <= b && b <= 'Z' {
  25. return b + ('a' - 'A')
  26. }
  27. return b
  28. }
  29. // isASCIIPrint returns whether s is ASCII and printable according to
  30. // https://tools.ietf.org/html/rfc20#section-4.2.
  31. func isASCIIPrint(s string) bool {
  32. for i := 0; i < len(s); i++ {
  33. if s[i] < ' ' || s[i] > '~' {
  34. return false
  35. }
  36. }
  37. return true
  38. }
  39. // asciiToLower returns the lowercase version of s if s is ASCII and printable,
  40. // and whether or not it was.
  41. func asciiToLower(s string) (lower string, ok bool) {
  42. if !isASCIIPrint(s) {
  43. return "", false
  44. }
  45. return strings.ToLower(s), true
  46. }