Source file src/net/http/internal/ascii/print.go

     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  
     5  package ascii
     6  
     7  import (
     8  	"strings"
     9  	"unicode"
    10  )
    11  
    12  // EqualFold is strings.EqualFold, ASCII only. It reports whether s and t
    13  // are equal, ASCII-case-insensitively.
    14  func EqualFold(s, t string) bool {
    15  	if len(s) != len(t) {
    16  		return false
    17  	}
    18  	for i := 0; i < len(s); i++ {
    19  		if lower(s[i]) != lower(t[i]) {
    20  			return false
    21  		}
    22  	}
    23  	return true
    24  }
    25  
    26  // lower returns the ASCII lowercase version of b.
    27  func lower(b byte) byte {
    28  	if 'A' <= b && b <= 'Z' {
    29  		return b + ('a' - 'A')
    30  	}
    31  	return b
    32  }
    33  
    34  // IsPrint returns whether s is ASCII and printable according to
    35  // https://tools.ietf.org/html/rfc20#section-4.2.
    36  func IsPrint(s string) bool {
    37  	for i := 0; i < len(s); i++ {
    38  		if s[i] < ' ' || s[i] > '~' {
    39  			return false
    40  		}
    41  	}
    42  	return true
    43  }
    44  
    45  // Is returns whether s is ASCII.
    46  func Is(s string) bool {
    47  	for i := 0; i < len(s); i++ {
    48  		if s[i] > unicode.MaxASCII {
    49  			return false
    50  		}
    51  	}
    52  	return true
    53  }
    54  
    55  // ToLower returns the lowercase version of s if s is ASCII and printable.
    56  func ToLower(s string) (lower string, ok bool) {
    57  	if !IsPrint(s) {
    58  		return "", false
    59  	}
    60  	return strings.ToLower(s), true
    61  }
    62  

View as plain text