Skip to content

Commit

Permalink
update the strings decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Sep 24, 2024
1 parent dcf2b9e commit 23589d8
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (vs Strings) Value() (driver.Value, error) {

// Scan implements the interface sql.Scanner to scan a sql value to the map.
func (vs *Strings) Scan(src any) error {
return decodestrings((*[]string)(vs), src, SliceSep)
return decodestrings(vs, src, SliceSep)
}

// Map is a map value type, which is encoded to a string or decoded from a []byte or string.
Expand All @@ -82,6 +82,11 @@ func DecodeMap[M ~map[string]T, T any](m *M, src any) error {
return decodemap(m, src)
}

// DecodeStrings decodes a string slice from string or []byte.
func DecodeStrings[S ~[]string](s *S, src any, sep string) error {
return decodestrings(s, src, sep)
}

func encodemap[M ~map[string]T, T any](m M) (s string, err error) {
if len(m) == 0 {
return
Expand Down Expand Up @@ -115,13 +120,17 @@ func decodemap[M ~map[string]T, T any](m *M, src any) (err error) {
return
}

func decodestrings(vs *[]string, src any, sep string) (err error) {
func decodestrings[S ~[]string](s *S, src any, sep string) (err error) {
if sep == "" {
panic("sqlx.DecodeStrings: sep must not be empty")
}

switch data := src.(type) {
case nil:
case []byte:
*vs = strings.Split(string(data), sep)
*s = strings.Split(string(data), sep)
case string:
*vs = strings.Split(data, sep)
*s = strings.Split(data, sep)
default:
err = fmt.Errorf("converting %T to []string is unsupported", src)
}
Expand Down

0 comments on commit 23589d8

Please sign in to comment.