gitee.com/quant1x/gox@v1.21.2/api/string_snake.go (about) 1 // Copyright (c) 2017, A. Stoewer <adrian.stoewer@rz.ifi.lmu.de> 2 // All rights reserved. 3 4 package api 5 6 import ( 7 "strings" 8 ) 9 10 // SnakeCase converts a string into snake case. 11 func SnakeCase(s string) string { 12 return delimiterCase(s, '_', false) 13 } 14 15 // UpperSnakeCase converts a string into snake case with capital letters. 16 func UpperSnakeCase(s string) string { 17 return delimiterCase(s, '_', true) 18 } 19 20 // delimiterCase converts a string into snake_case or kebab-case depending on the delimiter passed 21 // as second argument. When upperCase is true the result will be UPPER_SNAKE_CASE or UPPER-KEBAB-CASE. 22 func delimiterCase(s string, delimiter rune, upperCase bool) string { 23 s = strings.TrimSpace(s) 24 buffer := make([]rune, 0, len(s)+3) 25 26 adjustCase := toLower 27 if upperCase { 28 adjustCase = toUpper 29 } 30 31 var prev rune 32 var curr rune 33 for _, next := range s { 34 if isDelimiter(curr) { 35 if !isDelimiter(prev) { 36 buffer = append(buffer, delimiter) 37 } 38 } else if isUpper(curr) { 39 if isLower(prev) || (isUpper(prev) && isLower(next)) { 40 buffer = append(buffer, delimiter) 41 } 42 buffer = append(buffer, adjustCase(curr)) 43 } else if curr != 0 { 44 buffer = append(buffer, adjustCase(curr)) 45 } 46 prev = curr 47 curr = next 48 } 49 50 if len(s) > 0 { 51 if isUpper(curr) && isLower(prev) && prev != 0 { 52 buffer = append(buffer, delimiter) 53 } 54 buffer = append(buffer, adjustCase(curr)) 55 } 56 57 return string(buffer) 58 }