github.com/moreal/bencodex-go@v0.0.0-20231021172012-18277a477d15/internal/decoder/bytes.go (about)

     1  package decoder
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"fmt"
     7  	bencodex "github.com/moreal/bencodex-go/internal"
     8  )
     9  
    10  func (d *Decoder) decodeBytes(isUnicode bool) (bencodex.BencodexBytesLike, error) {
    11  	if d.data[d.cursor] < '0' || d.data[d.cursor] > '9' {
    12  		return bencodex.BencodexBytesLike{}, errors.New(fmt.Sprintf("bencode: invalid string field '%c', expected '0'~'9'", d.data[d.cursor]))
    13  	}
    14  	index := bytes.IndexByte(d.data[d.cursor:], ':')
    15  	if index == -1 {
    16  		return bencodex.BencodexBytesLike{}, errors.New(fmt.Sprintf("bencode: invalid string field '%c', expected ':'", d.data[d.cursor]))
    17  	}
    18  	index += d.cursor
    19  	stringLength, err := d.parseInt(d.data[d.cursor:index])
    20  	if err != nil {
    21  		return bencodex.BencodexBytesLike{}, err
    22  	}
    23  	index += 1
    24  	endIndex := index + int(stringLength)
    25  	if endIndex > d.length {
    26  		return bencodex.BencodexBytesLike{}, errors.New("bencode: not a valid bencoded string")
    27  	}
    28  	value := d.data[index:endIndex]
    29  	d.cursor = endIndex
    30  	if isUnicode {
    31  		return bencodex.NewString(bencodex.B2S(value)), nil
    32  	}
    33  
    34  	return bencodex.NewBytes(value), nil
    35  }