1

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?

2
  • Do we have any guarantees about the numbers in the input? E.g. are they always positive or can they be negative too? Also may the numbers have preceeding zeros, for example the number 10 may be written as 00010? Commented Aug 27, 2015 at 7:14
  • there are no guarantees about the input, its all parsed []byte from a configuration file at this point Commented Aug 28, 2015 at 15:18

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

hmm, still I'd like to elide the jumps from byte to string to int to byte, if there is a smoother way; if its not problem its not, it just seems less fluid and more trouble than it should
@blueblank: If you want to parse the characters into integers (and it seems that's what you want fin order to do the numerical comparison), then you need to convert to string in order to pass it into strconv.ParseInt.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.