Skip to content

Instantly share code, notes, and snippets.

@jeremyheiler
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyheiler/57759db394955254c3fb to your computer and use it in GitHub Desktop.
Save jeremyheiler/57759db394955254c3fb to your computer and use it in GitHub Desktop.
package bencode
import (
"fmt"
"io"
"reflect"
)
func Encode(w io.Writer, x interface{}) {
v := reflect.ValueOf(x)
switch v.Kind() {
case reflect.String:
fmt.Fprintf(w, "%d:%s", v.Len(), x)
case reflect.Int:
fmt.Fprintf(w, "i%de", x)
case reflect.Slice:
fmt.Fprint(w, "l")
for i := 0; i < v.Len(); i++ {
Encode(w, v.Index(i).Interface())
}
fmt.Fprint(w, "e")
case reflect.Map:
// TODO: ensure map keys are strings
// TODO: sort map by keys
fmt.Fprint(w, "d")
for _, e := range v.MapKeys() {
Encode(w, e.Interface())
Encode(w, v.MapIndex(e).Interface())
}
fmt.Fprint(w, "e")
default:
// TODO: error
fmt.Fprint(w, "#")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment