Reputation: 4894
I would simply like to do this without resorting to strconv & strings, but I am not proficient working in bytes only:
func rangeSeq(b *bytes.Buffer) ([][]byte, bool) {
q := bytes.Split(b.Bytes(), []byte{SEQ_RANGE})
if len(q) == 2 {
var ret [][]byte
il, lt := string(q[0]), string(q[1])
initial, err := strconv.ParseInt(il, 10, 64)
last, err := strconv.ParseInt(lt, 10, 64)
if err == nil {
if initial < last {
for i := initial; i <= last; i++ {
out := strconv.AppendInt([]byte{}, i, 10)
ret = append(ret, out)
}
}
return ret, true
}
}
return nil, false
}
suggestions?
Upvotes: 1
Views: 263
Reputation: 109388
There is no []byte
equivalent to the strconv.Parse* functions (see issue 2632). Using strconv is currently the easiest way to handle this.
You are ignoring the first error however, which is a bug. You can also shorten a couple things, and use the more common idiom of returning early instead of increasing indentation. I would also return an error, instead of a bool for more contextual information.
func rangeSeq(b *bytes.Buffer) ([][]byte, error) {
q := bytes.Split(b.Bytes(), sep)
if len(q) != 2 {
return nil, fmt.Errorf("invalid value: %s", b)
}
var ret [][]byte
initial, err := strconv.Atoi(string(q[0]))
if err != nil {
return nil, err
}
last, err := strconv.Atoi(string(q[1]))
if err != nil {
return nil, err
}
if initial < last {
for i := initial; i <= last; i++ {
ret = append(ret, strconv.AppendInt(nil, i, 10))
}
}
return ret, nil
}
Upvotes: 3