Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions strcase/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ strcase.Detect("helloworld") // strcase.FlatCase
strcase.Detect("") // strcase.FlatCase
```

The leading and the trailing separators are not taken into account, see
[Separators at the edges](#separators-at-the-edges).

Only the first 100 bytes of the string are inspected, so that the detection
stays cheap on long strings. A separator that appears later than that is not
taken into account.
Expand All @@ -98,6 +101,36 @@ Two rules deserve a note:
capitalizes the following letter; converting from `CamelCase` splits the
string into words.

## Separators at the edges

The leading and the trailing separators of a string are not separators: they
separate nothing, so they are standalone symbols, a part of the name (e.g. the
`__` of a private PHP property or the `_` of an unexported Go one).

Such symbols are carried over by the conversion as they are: they are neither
replaced nor removed, and they are not the word boundaries either.

```go
strcase.Convert("__hello_world").To(strcase.CamelCase) // __helloWorld
strcase.Convert("__hello_world").To(strcase.KebabCase) // __hello-world
strcase.Convert("__hello_world").To(strcase.FlatCase) // __helloworld
```

They are ignored by the detection as well, so the case of a string is the case
of its core:

```go
strcase.Detect("__hello_world") // strcase.SnakeCase
strcase.Detect("__helloWorld") // strcase.CamelCase
```

Thanks to that, the round trip is lossless:

```go
strcase.Convert("__hello_world").To(strcase.CamelCase) // __helloWorld
strcase.Convert("__helloWorld").To(strcase.SnakeCase) // __hello_world
```

## Abbreviations

When a camel case string is split into words, the abbreviations are recognized
Expand Down
73 changes: 69 additions & 4 deletions strcase/strcase.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ func (c Converter) To(target Mode) string {
// Converting a string to the case it already has returns it unchanged.
// [FlatCase] means that the case of the string is unknown, so converting from
// it is a no-op as well.
//
// The leading and the trailing separators of the string are standalone symbols,
// not the word boundaries, so they are carried over as they are: they are
// neither replaced nor removed.
func (c Mode) ConvertTo(target Mode, s string) string {
switch {
case c == target, c == FlatCase:
Expand Down Expand Up @@ -92,6 +96,10 @@ func (c Mode) sep() rune {
// one, a string containing a dash is a kebab case one, and a string with both
// lower and upper case letters is a camel case one.
//
// The leading and the trailing separators are standalone symbols, not the word
// boundaries, so they are not taken into account: the case is detected by the
// rest of the string.
//
// Only the first 100 bytes of the string are inspected, so that the detection
// stays cheap on long strings.
//
Expand All @@ -102,6 +110,17 @@ func Detect(s string) Mode {
return FlatCase // FlatCase used as a fallback value
}

_, core, _ := splitEdges(s)
return detectCore(core)
}

// detectCore detects the case of a string without the leading and the trailing
// separators.
func detectCore(s string) Mode {
if s == "" {
return FlatCase // FlatCase used as a fallback value
}

lowerFound := false
upperFound := false

Expand Down Expand Up @@ -135,16 +154,50 @@ func Detect(s string) Mode {
return FlatCase
}

// splitEdges splits the leading and the trailing separators of the string from
// the rest of it.
//
// The separators at the edges are standalone symbols: they separate nothing, so
// they are kept as they are by the conversions.
func splitEdges(s string) (prefix, core, suffix string) {
start := 0
for start < len(s) && isSep(s[start]) {
start++
}

end := len(s)
for end > start && isSep(s[end-1]) {
end--
}

return s[:start], s[start:end], s[end:]
}

// isSep reports whether the byte is a separator character.
//
// Only the ASCII separators are checked, so the byte-wise scanning of a UTF-8
// string is safe.
func isSep(b byte) bool {
return b == '_' || b == '-'
}

// toCamel removes the separator from the string and capitalizes the letter
// that follows it.
//
// The leading and the trailing separators are standalone symbols, not the word
// boundaries, so they are kept as they are.
func toCamel(s string, sep rune) string {
if s == "" {
return ""
}

rs := []rune(s)
prefix, core, suffix := splitEdges(s)

rs := []rune(core)
sb := &strings.Builder{}
sb.Grow(len(rs))
sb.Grow(len(rs) + len(prefix) + len(suffix))

sb.WriteString(prefix)

upperNext := false
for _, r := range rs {
Expand All @@ -160,6 +213,9 @@ func toCamel(s string, sep rune) string {
sb.WriteRune(r)
}
}

sb.WriteString(suffix)

return sb.String()
}

Expand Down Expand Up @@ -217,6 +273,9 @@ func fromCamel(s string, sep rune) string {

// replaceSep replaces the fromSep separator with the toSep one.
//
// The leading and the trailing separators are standalone symbols, not the word
// boundaries, so they are kept as they are.
//
// A noSep source separator means that the string has no separators at all and
// is returned as is; a noSep target separator removes the separators.
func replaceSep(s string, fromSep, toSep rune) string {
Expand All @@ -225,10 +284,14 @@ func replaceSep(s string, fromSep, toSep rune) string {
return s
}

prefix, core, suffix := splitEdges(s)

sb := &strings.Builder{}
sb.Grow(len([]rune(s)))
sb.Grow(len(s))

sb.WriteString(prefix)

for _, r := range s {
for _, r := range core {
if r == fromSep {
if toSep == noSep {
// flat case
Expand All @@ -240,5 +303,7 @@ func replaceSep(s string, fromSep, toSep rune) string {
}
}

sb.WriteString(suffix)

return sb.String()
}
149 changes: 147 additions & 2 deletions strcase/strcase_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,36 @@ func Test_toCamel(t *testing.T) {
sep: '_',
want: "v1Name",
},
{
name: "the leading separators are kept",
input: "__one_two",
sep: '_',
want: "__oneTwo",
},
{
name: "the trailing separators are kept",
input: "one_two__",
sep: '_',
want: "oneTwo__",
},
{
name: "the separators at both edges are kept",
input: "__one_two__",
sep: '_',
want: "__oneTwo__",
},
{
name: "the leading separators are not a word boundary",
input: "__one",
sep: '_',
want: "__one",
},
{
name: "the inner separators are a word boundary",
input: "one__two",
sep: '_',
want: "oneTwo",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -175,6 +205,18 @@ func Test_fromCamel(t *testing.T) {
sep: '_',
want: "v1_name",
},
{
name: "the leading separators are kept",
input: "_oneTwo",
sep: '_',
want: "_one_two",
},
{
name: "the trailing separators are kept",
input: "oneTwo__",
sep: '_',
want: "one_two__",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -208,10 +250,10 @@ func Test_replaceSep(t *testing.T) {
},
{
name: "hyphen to noSep",
inputStr: "bonjour_le-monde",
inputStr: "bonjour-le-monde",
fromSep: '-',
toSep: noSep,
want: "bonjour_lemonde",
want: "bonjourlemonde",
},
{
name: "noSep to anything",
Expand All @@ -220,6 +262,34 @@ func Test_replaceSep(t *testing.T) {
toSep: '#',
want: "bonjour-le-monde",
},
{
name: "the leading separators are not replaced",
inputStr: "__bonjour_le_monde",
fromSep: '_',
toSep: '-',
want: "__bonjour-le-monde",
},
{
name: "the trailing separators are not replaced",
inputStr: "bonjour_le_monde__",
fromSep: '_',
toSep: '-',
want: "bonjour-le-monde__",
},
{
name: "the leading separators are not removed",
inputStr: "__bonjour_le_monde",
fromSep: '_',
toSep: noSep,
want: "__bonjourlemonde",
},
{
name: "the trailing separators are not removed",
inputStr: "bonjour_le_monde__",
fromSep: '_',
toSep: noSep,
want: "bonjourlemonde__",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -228,3 +298,78 @@ func Test_replaceSep(t *testing.T) {
})
}
}

func Test_splitEdges(t *testing.T) {
tests := []struct {
name string
input string
wantPrefix string
wantCore string
wantSuffix string
}{
{
name: "empty string",
input: "",
wantPrefix: "",
wantCore: "",
wantSuffix: "",
},
{
name: "no separators",
input: "hello",
wantPrefix: "",
wantCore: "hello",
wantSuffix: "",
},
{
name: "the leading separators",
input: "__hello",
wantPrefix: "__",
wantCore: "hello",
wantSuffix: "",
},
{
name: "the trailing separators",
input: "hello__",
wantPrefix: "",
wantCore: "hello",
wantSuffix: "__",
},
{
name: "the separators at both edges",
input: "__hello__",
wantPrefix: "__",
wantCore: "hello",
wantSuffix: "__",
},
{
name: "the inner separators",
input: "hello_world",
wantPrefix: "",
wantCore: "hello_world",
wantSuffix: "",
},
{
name: "the separators only",
input: "__",
wantPrefix: "__",
wantCore: "",
wantSuffix: "",
},
{
name: "the mixed separators",
input: "__hello--world--",
wantPrefix: "__",
wantCore: "hello--world",
wantSuffix: "--",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotPrefix, gotCore, gotSuffix := splitEdges(tt.input)
assert.Equal(t, tt.wantPrefix, gotPrefix)
assert.Equal(t, tt.wantCore, gotCore)
assert.Equal(t, tt.wantSuffix, gotSuffix)
})
}
}
Loading
Loading