From a85f348fff95e77b846a1175ff030bb32024b7e9 Mon Sep 17 00:00:00 2001 From: Brad Reed Date: Mon, 19 Jun 2017 22:15:04 +0100 Subject: [PATCH] Test and improved, non-stupid camel case conversion --- gen/generator.go | 54 ++++++++++++++++++++++++++++++++++++++++--- gen/generator_test.go | 22 ++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/gen/generator.go b/gen/generator.go index 4e8c5b8..cae11b6 100644 --- a/gen/generator.go +++ b/gen/generator.go @@ -11,7 +11,6 @@ import ( "strconv" "strings" "unicode" - "unicode/utf8" ) const pkgWriter = "github.com/mailru/easyjson/jwriter" @@ -382,12 +381,61 @@ func (DefaultFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) // LowerCamelCaseFieldNamer type LowerCamelCaseFieldNamer struct {} + +func isLower(b byte) bool { + return b <= 122 && b >= 97 +} + +func isUpper(b byte) bool { + return b >= 65 && b <= 90 +} + +func isNumeric(b byte) bool { + return b >= 48 && b <= 57 +} +// convert HTTPRestClient to httpRestClient func lowerFirst(s string) string { if s == "" { return "" } - r, n := utf8.DecodeRuneInString(s) - return string(unicode.ToLower(r)) + s[n:] + + str := "" + strlen := len(s) + + /** + Loop each char + If is uppercase: + If is first char, LOWER it + If the following char is lower, LEAVE it + If the following char is upper OR numeric, LOWER it + If is the end of string, LEAVE it + Else lowercase + */ + + foundLower := false + for i := range s { + ch := s[i] + if isUpper(ch) { + if i == 0 { + str += string(ch + 32) + } else if !foundLower { // Currently just a stream of capitals, eg JSONRESTS[erver] + if strlen > (i+1) && isLower(s[i+1]) { + // Next char is lower, keep this a capital + str += string(ch) + } else { + // Either at end of string or next char is capital + str += string(ch + 32) + } + } else { + str += string(ch) + } + } else { + foundLower = true + str += string(ch) + } + } + + return str } func (LowerCamelCaseFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { diff --git a/gen/generator_test.go b/gen/generator_test.go index 62c03f0..0c9d278 100644 --- a/gen/generator_test.go +++ b/gen/generator_test.go @@ -28,6 +28,28 @@ func TestCamelToSnake(t *testing.T) { } } +func TestCamelToLowerCamel(t *testing.T) { + for i, test := range []struct { + In, Out string + }{ + {"", ""}, + {"A", "a"}, + {"SimpleExample", "simpleExample"}, + {"internalField", "internalField"}, + + {"SomeHTTPStuff", "someHTTPStuff"}, + {"WriteJSON", "writeJSON"}, + {"HTTP2Server", "http2Server"}, + + {"JSONHTTPRPCServer", "jsonhttprpcServer"}, // nothing can be done here without a dictionary + } { + got := lowerFirst(test.In) + if got != test.Out { + t.Errorf("[%d] lowerFirst(%s) = %s; want %s", i, test.In, got, test.Out) + } + } +} + func TestJoinFunctionNameParts(t *testing.T) { for i, test := range []struct { keepFirst bool