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

add Duration.from_iso8601/1 #13473

Merged
merged 20 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from 18 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
48 changes: 48 additions & 0 deletions lib/elixir/lib/calendar/duration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,52 @@ defmodule Duration do
microsecond: {-ms, p}
}
end

@doc """
Parses an ISO 8601 formatted duration string to a `Duration` struct.

A decimal fraction may be specified for seconds only, using either a comma or a full stop.

## Examples

iex> Duration.from_iso8601("P1Y2M3DT4H5M6S")
{:ok, %Duration{year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6}}
iex> Duration.from_iso8601("PT10H30M")
{:ok, %Duration{hour: 10, minute: 30, second: 0}}
iex> Duration.from_iso8601("P3Y-2MT3H")
{:ok, %Duration{year: 3, month: -2, hour: 3}}
iex> Duration.from_iso8601("P1YT4.650S")
{:ok, %Duration{year: 1, second: 4, microsecond: {650000, 3}}}

"""
@spec from_iso8601(String.t()) :: {:ok, t} | {:error, atom}
def from_iso8601(string) when is_binary(string) do
case Calendar.ISO.parse_duration(string) do
{:ok, duration} ->
{:ok, new!(duration)}

error ->
error
end
end

@doc """
Same as from_iso8601/1 but raises an ArgumentError.
josevalim marked this conversation as resolved.
Show resolved Hide resolved

## Examples

iex> Duration.from_iso8601!("P1Y2M3DT4H5M6S")
%Duration{year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6}

"""
@spec from_iso8601!(String.t()) :: t
def from_iso8601!(string) when is_binary(string) do
case from_iso8601(string) do
{:ok, duration} ->
duration

{:error, reason} ->
raise ArgumentError, ~s/failed to parse duration "#{string}". reason: #{inspect(reason)}/
end
end
end
165 changes: 163 additions & 2 deletions lib/elixir/lib/calendar/iso.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ defmodule Calendar.ISO do

The standard library supports a minimal set of possible ISO 8601 features.
Specifically, the parser only supports calendar dates and does not support
ordinal and week formats.
ordinal and week formats. Additionally, it supports parsing ISO 8601
formatted durations, including negative time units and fractional seconds.

By default Elixir only parses extended-formatted date/times. You can opt-in
to parse basic-formatted date/times.
Expand All @@ -29,7 +30,7 @@ defmodule Calendar.ISO do

Elixir does not support reduced accuracy formats (for example, a date without
the day component) nor decimal precisions in the lowest component (such as
`10:01:25,5`). No functions exist to parse ISO 8601 durations or time intervals.
`10:01:25,5`).

#### Examples

Expand Down Expand Up @@ -663,6 +664,166 @@ defmodule Calendar.ISO do
end
end

@doc """
Parses an ISO 8601 formatted duration string to a list of `Duration` compabitble unit pairs.

See `Duration.from_iso8601/1`.

tfiedlerdejanze marked this conversation as resolved.
Show resolved Hide resolved
"""
@doc since: "1.17.0"
@spec parse_duration(String.t()) :: {:ok, [Duration.unit_pair()]} | {:error, atom()}
def parse_duration(string) do
tfiedlerdejanze marked this conversation as resolved.
Show resolved Hide resolved
with {:ok, acc, rest, buffer} <- parse_duration(:period, string, %{time: false}),
{:ok, acc, rest, buffer} <- parse_duration(:year, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:month, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:week, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:day, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:time, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:hour, rest, acc, buffer),
{:ok, acc, rest, buffer} <- parse_duration(:minute, rest, acc, buffer),
{:ok, acc, "", ""} <- parse_duration(:second, rest, acc, buffer) do
{:ok,
acc
|> Map.take([:year, :month, :week, :day, :hour, :minute, :second, :microsecond])
|> Keyword.new()}
else
{:error, error} ->
{:error, error}

_ ->
{:error, :invalid_duration}
end
end

defp parse_duration(:period, <<"P", rest::binary>>, acc) do
{:ok, acc, rest, ""}
end

defp parse_duration(:period, _rest, _acc) do
{:error, :invalid_duration}
end

for {part, designator} <- [year: "Y", month: "M", day: "D", week: "W"] do
defp parse_duration(unquote(part), <<c, rest::binary>>, acc, buffer)
when c in ?0..?9 or c in [?,, ?., ?-] do
parse_duration(unquote(part), rest, acc, <<buffer::binary, c>>)
end

defp parse_duration(unquote(part), <<unquote(designator), rest::binary>>, acc, "-" <> buffer) do
with {:ok, acc} <- parse_duration_buffer(unquote(part), acc, buffer, -1) do
{:ok, acc, rest, ""}
end
end

defp parse_duration(unquote(part), <<unquote(designator), rest::binary>>, acc, buffer) do
with {:ok, acc} <- parse_duration_buffer(unquote(part), acc, buffer) do
{:ok, acc, rest, ""}
end
end

defp parse_duration(unquote(part), rest, acc, buffer) do
{:ok, acc, rest, buffer}
end
end

defp parse_duration(:time, <<"T", rest::binary>>, acc, "") do
{:ok, Map.put(acc, :time, true), rest, ""}
end

defp parse_duration(:time, rest, acc, buffer) do
{:ok, acc, rest, buffer}
end

for {part, designator} <- [hour: "H", minute: "M", second: "S"] do
defp parse_duration(unquote(part), <<c, rest::binary>>, acc, buffer)
when c in ?0..?9 or c in [?,, ?., ?-] do
parse_duration(unquote(part), rest, acc, <<buffer::binary, c>>)
end

defp parse_duration(
unquote(part),
<<unquote(designator), rest::binary>>,
%{time: true} = acc,
"-" <> buffer
) do
with {:ok, acc} <- parse_duration_buffer(unquote(part), acc, buffer, -1) do
{:ok, acc, rest, ""}
end
end

defp parse_duration(
unquote(part),
<<unquote(designator), rest::binary>>,
%{time: true} = acc,
buffer
) do
with {:ok, acc} <- parse_duration_buffer(unquote(part), acc, buffer) do
{:ok, acc, rest, ""}
end
end

defp parse_duration(unquote(part), <<unquote(designator), _::binary>>, _acc, _buffer) do
{:error, :invalid_duration}
end

defp parse_duration(unquote(part), rest, acc, buffer) do
{:ok, acc, rest, buffer}
end
end

defp parse_duration_buffer(unit, acc, buffer, multiplier \\ 1)

defp parse_duration_buffer(:second, acc, buffer, multiplier) do
case parse_fraction_duration(buffer, "") do
{second, ""} ->
{:ok, Map.put(acc, :second, multiplier * second)}

{second, microsecond} ->
case parse_microsecond(microsecond) do
{{ms, precision}, ""} ->
{:ok,
acc
|> Map.put(:second, multiplier * second)
|> Map.put(:microsecond, {multiplier * ms, precision})}

_ ->
{:error, :invalid_duration}
end

error ->
error
end
end

defp parse_duration_buffer(unit, acc, buffer, multiplier) do
case Integer.parse(buffer) do
{value, ""} ->
{:ok, Map.put(acc, unit, multiplier * value)}

_ ->
{:error, :invalid_unit_value}
end
end

defp parse_fraction_duration(<<>>, ""), do: {0, ""}
defp parse_fraction_duration(<<>>, second), do: {String.to_integer(second), ""}

defp parse_fraction_duration(<<c, rest::binary>>, second) when c in ?0..?9 do
parse_fraction_duration(rest, <<second::binary, c>>)
end

defp parse_fraction_duration(<<c, rest::binary>>, "") when c in [?., ?,] do
{0, <<c, rest::binary>>}
end

defp parse_fraction_duration(<<c, rest::binary>>, second) when c in [?., ?,] do
{String.to_integer(second), <<c, rest::binary>>}
end

defp parse_fraction_duration(_, _) do
{:error, :invalid_unit_value}
end

@doc """
Returns the `t:Calendar.iso_days/0` format of the specified date.

Expand Down
86 changes: 86 additions & 0 deletions lib/elixir/test/elixir/calendar/duration_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,90 @@ defmodule DurationTest do
microsecond: {0, 0}
}
end

test "from_iso8601/1" do
assert Duration.from_iso8601("P1Y2M3DT4H5M6S") ==
{:ok, %Duration{year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6}}

assert Duration.from_iso8601("P3WT5H3M") == {:ok, %Duration{week: 3, hour: 5, minute: 3}}
assert Duration.from_iso8601("PT5H3M") == {:ok, %Duration{hour: 5, minute: 3}}
assert Duration.from_iso8601("P1Y2M3D") == {:ok, %Duration{year: 1, month: 2, day: 3}}
assert Duration.from_iso8601("PT4H5M6S") == {:ok, %Duration{hour: 4, minute: 5, second: 6}}
assert Duration.from_iso8601("P1Y2M") == {:ok, %Duration{year: 1, month: 2}}
assert Duration.from_iso8601("P3D") == {:ok, %Duration{day: 3}}
assert Duration.from_iso8601("PT4H5M") == {:ok, %Duration{hour: 4, minute: 5}}
assert Duration.from_iso8601("PT6S") == {:ok, %Duration{second: 6}}
assert Duration.from_iso8601("P2M4Y") == {:error, :invalid_duration}
assert Duration.from_iso8601("P4Y2W3Y") == {:error, :invalid_duration}
assert Duration.from_iso8601("P5HT4MT3S") == {:error, :invalid_duration}
assert Duration.from_iso8601("P5H3HT4M") == {:error, :invalid_duration}
assert Duration.from_iso8601("invalid") == {:error, :invalid_duration}
end

test "from_iso8601!/1" do
assert Duration.from_iso8601!("P1Y2M3DT4H5M6S") == %Duration{
year: 1,
month: 2,
day: 3,
hour: 4,
minute: 5,
second: 6
}

assert Duration.from_iso8601!("P3WT5H3M") == %Duration{week: 3, hour: 5, minute: 3}
assert Duration.from_iso8601!("PT5H3M") == %Duration{hour: 5, minute: 3}
assert Duration.from_iso8601!("P1Y2M3D") == %Duration{year: 1, month: 2, day: 3}
assert Duration.from_iso8601!("PT4H5M6S") == %Duration{hour: 4, minute: 5, second: 6}
assert Duration.from_iso8601!("P1Y2M") == %Duration{year: 1, month: 2}
assert Duration.from_iso8601!("P3D") == %Duration{day: 3}
assert Duration.from_iso8601!("PT4H5M") == %Duration{hour: 4, minute: 5}
assert Duration.from_iso8601!("PT6S") == %Duration{second: 6}
assert Duration.from_iso8601!("PT1,6S") == %Duration{second: 1, microsecond: {600_000, 1}}
assert Duration.from_iso8601!("PT-1.6S") == %Duration{second: -1, microsecond: {-600_000, 1}}
assert Duration.from_iso8601!("PT.6S") == %Duration{second: 0, microsecond: {600_000, 1}}
assert Duration.from_iso8601!("PT-.6S") == %Duration{second: 0, microsecond: {-600_000, 1}}
tfiedlerdejanze marked this conversation as resolved.
Show resolved Hide resolved

assert Duration.from_iso8601!("PT-1.234567S") == %Duration{
second: -1,
microsecond: {-234_567, 6}
}

assert Duration.from_iso8601!("PT1.12345678S") == %Duration{
second: 1,
microsecond: {123_456, 6}
}

assert Duration.from_iso8601!("P3Y4W-3DT-6S") == %Duration{
year: 3,
week: 4,
day: -3,
second: -6
}

assert Duration.from_iso8601!("PT-4.23S") == %Duration{second: -4, microsecond: {-230_000, 2}}

assert_raise ArgumentError,
~s/failed to parse duration "P5H3HT4M". reason: :invalid_duration/,
fn ->
Duration.from_iso8601!("P5H3HT4M")
end

assert_raise ArgumentError,
~s/failed to parse duration "P4Y2W3Y". reason: :invalid_duration/,
fn ->
Duration.from_iso8601!("P4Y2W3Y")
end

assert_raise ArgumentError,
~s/failed to parse duration "invalid". reason: :invalid_duration/,
fn ->
Duration.from_iso8601!("invalid")
end

assert_raise ArgumentError,
~s/failed to parse duration "P4.5YT6S". reason: :invalid_unit_value/,
fn ->
Duration.from_iso8601!("P4.5YT6S")
end
end
end