Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions lib/bencode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ defmodule Bencode do
int = num |> Integer.parse |> elem(0)

offset = String.length(num) + 1
tail = binary_part(rest, offset, byte_size(rest) - offset)
tail = String.slice rest, offset, String.length(rest) - offset

{int, tail}
end
Expand All @@ -114,11 +114,11 @@ defmodule Bencode do

int = size |> Integer.parse |> elem(0)
prefix = String.length(size) + 1
string = binary_part(data, prefix, int)

string = String.slice data, prefix, int

offset = prefix + int
tail = binary_part(data, offset, byte_size(data) - offset)
tail = String.slice data, offset, String.length(data) - offset

{string, tail}
end
Expand Down Expand Up @@ -151,7 +151,7 @@ defmodule Bencode do
def encode!(data) when is_map(data), do: Enum.reduce(data, "d", &(&2 <> encode!(&1))) <> "e"
def encode!(data) when is_atom(data), do: data |> Atom.to_string |> encode!
def encode!({k, v}), do: encode!(k) <> encode!(v)
def encode!(data), do: (data |> byte_size |> Integer.to_string) <> ":" <> data
def encode!(data), do: (data |> String.length |> Integer.to_string) <> ":" <> data

@doc """
Encode Elixir data structures to a Bencode bitstring.
Expand Down
10 changes: 9 additions & 1 deletion test/bencode_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ defmodule BencodeTest do
test "Decode empty string with faulty tail" do
assert {:error, :trailing_data} === decode("0:test")
end

test "Decode unicode string" do
assert {:ok, "exposé"} === decode("6:exposé")
end

test "Decode invalid integer" do
assert {:error, :invalid_format} === decode("i2")
Expand Down Expand Up @@ -110,14 +114,18 @@ defmodule BencodeTest do
test "Decode map with tail" do
assert {:error, :trailing_data} === decode("dei")
end

test "encode integer" do
assert "i42e" === encode!(42)
end

test "encode string" do
assert "4:spam" === encode!("spam")
end

test "encode unicode string" do
assert "6:exposé" === encode!("exposé")
end

test "encode atom" do
assert "4:spam" === encode!(:spam)
Expand Down