zf

zenflows testing
git clone https://s.sonu.ch/~srfsh/zf.git
Log | Files | Refs | Submodules | README | LICENSE

time.ex (1081B)


      1 defmodule Postgrex.Extensions.Time do
      2   @moduledoc false
      3   import Postgrex.BinaryUtils, warn: false
      4   use Postgrex.BinaryExtension, send: "time_send"
      5 
      6   def encode(_) do
      7     quote location: :keep do
      8       %Time{calendar: Calendar.ISO} = time ->
      9         unquote(__MODULE__).encode_elixir(time)
     10 
     11       other ->
     12         raise DBConnection.EncodeError, Postgrex.Utils.encode_msg(other, Time)
     13     end
     14   end
     15 
     16   def decode(_) do
     17     quote location: :keep do
     18       <<8::int32(), microsecs::int64()>> ->
     19         unquote(__MODULE__).microsecond_to_elixir(microsecs)
     20     end
     21   end
     22 
     23   ## Helpers
     24 
     25   def encode_elixir(%Time{hour: hour, minute: min, second: sec, microsecond: {usec, _}})
     26       when hour in 0..23 and min in 0..59 and sec in 0..59 and usec in 0..999_999 do
     27     time = {hour, min, sec}
     28     <<8::int32(), :calendar.time_to_seconds(time) * 1_000_000 + usec::int64()>>
     29   end
     30 
     31   def microsecond_to_elixir(microsec) do
     32     sec = div(microsec, 1_000_000)
     33     microsec = rem(microsec, 1_000_000)
     34 
     35     sec
     36     |> :calendar.seconds_to_time()
     37     |> Time.from_erl!({microsec, 6})
     38   end
     39 end