in starlark/library.go [2044:2090]
func string_split(_ *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
recv := string(b.Receiver().(String))
var sep_ Value
maxsplit := -1
if err := UnpackPositionalArgs(b.Name(), args, kwargs, 0, &sep_, &maxsplit); err != nil {
return nil, err
}
var res []string
if sep_ == nil || sep_ == None {
// special case: split on whitespace
if maxsplit < 0 {
res = strings.Fields(recv)
} else if b.Name() == "split" {
res = splitspace(recv, maxsplit)
} else { // rsplit
res = rsplitspace(recv, maxsplit)
}
} else if sep, ok := AsString(sep_); ok {
if sep == "" {
return nil, fmt.Errorf("split: empty separator")
}
// usual case: split on non-empty separator
if maxsplit < 0 {
res = strings.Split(recv, sep)
} else if b.Name() == "split" {
res = strings.SplitN(recv, sep, maxsplit+1)
} else { // rsplit
res = strings.Split(recv, sep)
if excess := len(res) - maxsplit; excess > 0 {
res[0] = strings.Join(res[:excess], sep)
res = append(res[:1], res[excess:]...)
}
}
} else {
return nil, fmt.Errorf("split: got %s for separator, want string", sep_.Type())
}
list := make([]Value, len(res))
for i, x := range res {
list[i] = String(x)
}
return NewList(list), nil
}