Last active
August 29, 2015 14:07
-
-
Save jeremyheiler/57759db394955254c3fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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