package bencode
import (
- "bufio"
"bytes"
"fmt"
"io"
UnmarshalBencode([]byte) error
}
-// Marshal the value 'v' to the bencode form, return the result as []byte and an
-// error if any.
+// Marshal the value 'v' to the bencode form, return the result as []byte and
+// an error if any.
func Marshal(v interface{}) ([]byte, error) {
var buf bytes.Buffer
- e := Encoder{w: bufio.NewWriter(&buf)}
+ e := Encoder{w: &buf}
err := e.Encode(v)
if err != nil {
return nil, err
}
func NewEncoder(w io.Writer) *Encoder {
- return &Encoder{w: bufio.NewWriter(w)}
+ return &Encoder{w: w}
}
}
type Encoder struct {
- w interface {
- Flush() error
- io.Writer
- WriteString(string) (int, error)
- }
+ w io.Writer
scratch [64]byte
}
}
}()
e.reflectValue(reflect.ValueOf(v))
- return e.w.Flush()
+ return nil
}
type string_values []reflect.Value
}
func (e *Encoder) writeString(s string) {
- _, err := e.w.WriteString(s)
- if err != nil {
- panic(err)
+ for s != "" {
+ n := copy(e.scratch[:], s)
+ s = s[n:]
+ e.write(e.scratch[:n])
}
}
e.writeString("i0e")
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
e.writeString("i")
+ b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
e.write(b)
e.writeString("e")
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
e.writeString("i")
+ b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
e.write(b)
e.writeString("e")
case reflect.String: