Skip to content

Commit 7554064

Browse files
sabiwarajosevalim
authored andcommitted
Fix bugs in binary_slice/2 (#12045)
1 parent e81e9f7 commit 7554064

File tree

2 files changed

+20
-20
lines changed

2 files changed

+20
-20
lines changed

lib/elixir/lib/kernel.ex

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4649,29 +4649,22 @@ defmodule Kernel do
46494649
when is_binary(binary) and step > 0 do
46504650
total = byte_size(binary)
46514651

4652-
first =
4653-
case first < 0 do
4654-
true -> max(first + total, 0)
4655-
false -> first
4656-
end
4652+
first = if first < 0, do: max(first + total, 0), else: first
4653+
last = if last < 0, do: last + total, else: last
46574654

4658-
last =
4659-
case last < 0 do
4660-
true -> last + total
4661-
false -> last
4662-
end
4655+
amount = last - first + 1
46634656

4664-
case first < total do
4665-
true ->
4666-
part = binary_part(binary, first, min(total - first, last - first + 1))
4667-
4668-
case step do
4669-
1 -> part
4670-
_ -> for <<byte, _::size(step - 1)-bytes <- part>>, into: "", do: <<byte>>
4671-
end
4657+
if first < total and amount > 0 do
4658+
part = binary_part(binary, first, min(amount, total - first))
46724659

4673-
false ->
4674-
""
4660+
if step == 1 do
4661+
part
4662+
else
4663+
<<first_byte, rest::binary>> = part
4664+
for <<_::size(step - 1)-bytes, byte <- rest>>, into: <<first_byte>>, do: <<byte>>
4665+
end
4666+
else
4667+
""
46754668
end
46764669
end
46774670

lib/elixir/test/elixir/kernel_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,13 @@ defmodule KernelTest do
14241424
assert match?(x when ceil(x) == 1, 0.2)
14251425
end
14261426

1427+
test "binary_slice/2" do
1428+
assert binary_slice("abc", -1..0) == ""
1429+
assert binary_slice("abc", -5..-5) == ""
1430+
assert binary_slice("x", 0..0//2) == "x"
1431+
assert binary_slice("abcde", 1..3//2) == "bd"
1432+
end
1433+
14271434
test "sigil_U/2" do
14281435
assert ~U[2015-01-13 13:00:07.123Z] == %DateTime{
14291436
calendar: Calendar.ISO,

0 commit comments

Comments
 (0)