From afe50dd881ca58c6331cc84b151df9bafd9e82e2 Mon Sep 17 00:00:00 2001 From: codecrafters-bot Date: Mon, 3 Jun 2024 16:03:29 +0000 Subject: init [skip ci] --- cmd/mybittorrent/main.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 cmd/mybittorrent/main.go (limited to 'cmd/mybittorrent/main.go') diff --git a/cmd/mybittorrent/main.go b/cmd/mybittorrent/main.go new file mode 100644 index 0000000..ba70193 --- /dev/null +++ b/cmd/mybittorrent/main.go @@ -0,0 +1,63 @@ +package main + +import ( + // Uncomment this line to pass the first stage + // "encoding/json" + "fmt" + "os" + "strconv" + "unicode" + // bencode "github.com/jackpal/bencode-go" // Available if you need it! +) + +// Example: +// - 5:hello -> hello +// - 10:hello12345 -> hello12345 +func decodeBencode(bencodedString string) (interface{}, error) { + if unicode.IsDigit(rune(bencodedString[0])) { + var firstColonIndex int + + for i := 0; i < len(bencodedString); i++ { + if bencodedString[i] == ':' { + firstColonIndex = i + break + } + } + + lengthStr := bencodedString[:firstColonIndex] + + length, err := strconv.Atoi(lengthStr) + if err != nil { + return "", err + } + + return bencodedString[firstColonIndex+1 : firstColonIndex+1+length], nil + } else { + return "", fmt.Errorf("Only strings are supported at the moment") + } +} + +func main() { + // You can use print statements as follows for debugging, they'll be visible when running tests. + fmt.Println("Logs from your program will appear here!") + + command := os.Args[1] + + if command == "decode" { + // Uncomment this block to pass the first stage + // + // bencodedValue := os.Args[2] + // + // decoded, err := decodeBencode(bencodedValue) + // if err != nil { + // fmt.Println(err) + // return + // } + // + // jsonOutput, _ := json.Marshal(decoded) + // fmt.Println(string(jsonOutput)) + } else { + fmt.Println("Unknown command: " + command) + os.Exit(1) + } +} -- cgit v1.2.3