Skip to content

Commit 8914dcd

Browse files
authored
Fix Integer.undigits/2 to validate negative out-of-range digits (#15160)
The validation was asymmetric - it rejected positive digits >= base but silently accepted negative digits <= -base. This fix adds the missing check for negative out-of-range digits.
1 parent 2db87eb commit 8914dcd

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

lib/elixir/lib/integer.ex

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,8 +297,9 @@ defmodule Integer do
297297

298298
defp undigits([], _base, acc), do: acc
299299

300-
defp undigits([digit | _], base, _) when is_integer(digit) and digit >= base,
301-
do: raise(ArgumentError, "invalid digit #{digit} in base #{base}")
300+
defp undigits([digit | _], base, _)
301+
when is_integer(digit) and (digit >= base or digit <= -base),
302+
do: raise(ArgumentError, "invalid digit #{digit} in base #{base}")
302303

303304
defp undigits([digit | tail], base, acc) when is_integer(digit),
304305
do: undigits(tail, base, acc * base + digit)

lib/elixir/test/elixir/integer_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ defmodule IntegerTest do
144144
assert_raise ArgumentError, "invalid digit 17 in base 16", fn ->
145145
Integer.undigits([1, 2, 17], 16)
146146
end
147+
148+
assert_raise ArgumentError, "invalid digit -10 in base 10", fn ->
149+
Integer.undigits([-10], 10)
150+
end
151+
152+
assert_raise ArgumentError, "invalid digit -17 in base 16", fn ->
153+
Integer.undigits([1, 2, -17], 16)
154+
end
147155
end
148156

149157
test "parse/2" do

0 commit comments

Comments
 (0)