Skip to content

Commit

Permalink
Add IsStr check function
Browse files Browse the repository at this point in the history
  • Loading branch information
demdxx committed Sep 24, 2023
1 parent 7c55a9f commit 50bfa3b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ func TryToString(v any) (string, error) {
return TryStr(v)
}

// IsStr returns true if value is string
func IsStr(v any) bool {
if v == nil {
return false
}
_, ok := v.(string)
return ok
}

// IsStrContainsOf returns true if input string contains only chars from subset
func IsStrContainsOf(s, subset string) bool {
if len(s) == 0 {
Expand Down
19 changes: 19 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ func TestToString(t *testing.T) {
}
}

func TestIsStr(t *testing.T) {
tests := []struct {
value any
target bool
}{
{value: 1, target: false},
{value: nil, target: false},
{value: int8(1), target: false},
{value: int16(1), target: false},
{value: []byte("notstr"), target: false},
{value: []int8{1, 2, 3, 4, 5}, target: false},
{value: []any{'1', '2', '3'}, target: false},
{value: "str", target: true},
}
for _, test := range tests {
assert.Equal(t, IsStr(test.value), test.target)
}
}

func BenchmarkToStringByReflect(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
Expand Down

0 comments on commit 50bfa3b

Please sign in to comment.