github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/protoc-gen-toolkit/gentoolkit/utils.go (about)

     1  /*
     2  Copyright [2014] - [2023] The Last.Backend authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package gentoolkit
    18  
    19  func camel(s string) string {
    20  	if s == "" {
    21  		return ""
    22  	}
    23  	t := make([]byte, 0, 32)
    24  	i := 0
    25  	if s[0] == '_' {
    26  		// Need a capital letter; drop the '_'.
    27  		t = append(t, 'X')
    28  		i++
    29  	}
    30  	// Invariant: if the next letter is lower case, it must be converted
    31  	// to upper case.
    32  	// That is, we process a word at a time, where words are marked by _ or
    33  	// upper case letter. Digits are treated as words.
    34  	for ; i < len(s); i++ {
    35  		c := s[i]
    36  		if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
    37  			continue // Skip the underscore in s.
    38  		}
    39  		if isASCIIDigit(c) {
    40  			t = append(t, c)
    41  			continue
    42  		}
    43  		// Assume we have a letter now - if not, it's a bogus identifier.
    44  		// The next word is a sequence of characters that must start upper case.
    45  		if isASCIILower(c) {
    46  			c ^= ' ' // Make it a capital letter.
    47  		}
    48  		t = append(t, c) // Guaranteed not lower case.
    49  		// Accept lower case sequence that follows.
    50  		for i+1 < len(s) && isASCIILower(s[i+1]) {
    51  			i++
    52  			t = append(t, s[i])
    53  		}
    54  	}
    55  	return string(t)
    56  }
    57  
    58  // And now lots of helper functions.
    59  
    60  // Is c an ASCII lower-case letter?
    61  func isASCIILower(c byte) bool {
    62  	return 'a' <= c && c <= 'z'
    63  }
    64  
    65  // Is c an ASCII digit?
    66  func isASCIIDigit(c byte) bool {
    67  	return '0' <= c && c <= '9'
    68  }