Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a custom string_to_float/1 function instead of plain String.to_float for ensure_numeric #221

Merged
merged 3 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion lib/geo/json/decoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ defmodule Geo.JSON.Decoder do

str when is_binary(str) ->
try do
String.to_float(str)
Geo.Utils.string_to_float!(str)
catch
ArgumentError ->
raise ArgumentError, "expected a numeric coordinate, got the string #{inspect(str)}"
Expand Down
25 changes: 25 additions & 0 deletions lib/geo/utils.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
defmodule Geo.Utils do
@moduledoc false

@spec string_to_float(String.t()) :: {:ok, float()} | {:error, term}
def string_to_float(str) when is_binary(str) do
case Float.parse(str) do
:error ->
{:error, :bad_arg}

{flt, ""} ->
{:ok, flt}

{_flt, _rest} ->
{:error, :bad_arg}
end
end

@spec string_to_float(String.t()) :: float()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
@spec string_to_float(String.t()) :: float()
@spec string_to_float!(String.t()) :: float() | no_return()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

huh, TIL about no_return, I'll add the test shortly

def string_to_float!(str) when is_binary(str) do
case string_to_float(str) do
{:ok, flt} ->
flt

{:error, :bad_arg} ->
raise ArgumentError, "given string is not a textual representation of a float"
end
end

@doc """
Turns a hex string or an integer of base 16 into its floating point
representation.
Expand Down