Skip to content

Commit

Permalink
Fix parsing of timestamp part in ULIDs for small timestamp values
Browse files Browse the repository at this point in the history
  • Loading branch information
ad-si committed Feb 22, 2020
1 parent e7b55cd commit 258df47
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
10 changes: 4 additions & 6 deletions tasklite-core/source/Utils.hs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,13 @@ parseUtc utcText =
parseUlidUtcSection :: Text -> Maybe DateTime
parseUlidUtcSection encodedUtc = do
let
decodedUtc = (Crock.decode . unpack) encodedUtc
decodedUtcMaybe = (Crock.decode . unpack) encodedUtc
getElapsed val = Elapsed $ Seconds $ val `div` 1000
getMilliSeconds val =
readMaybe $ T.unpack $ T.takeEnd 3 $ show val :: Maybe Int64

elapsed <- fmap getElapsed decodedUtc
milliSeconds <- getMilliSeconds decodedUtc
elapsed <- fmap getElapsed decodedUtcMaybe
milliSecPart <- fmap (`mod` 1000) decodedUtcMaybe

let nanoSeconds = NanoSeconds $ milliSeconds * 1000000
let nanoSeconds = NanoSeconds $ milliSecPart * 1000000

pure $ timeGetDateTimeOfDay $ ElapsedP elapsed nanoSeconds

Expand Down
16 changes: 16 additions & 0 deletions tasklite-core/test/Spec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ import Migrations
-- | and therefore the order must not be changed
testSuite :: Config -> DateTime -> Sql.Connection -> SpecWith ()
testSuite conf now connection = do
describe "Utils" $ do
it "correctly parses beginning of UNIX epoch" $ do
(parseUlidUtcSection "0000000000")
`shouldBe`
(Just $ timeGetDateTimeOfDay $ Elapsed 0)

it "correctly parses 36 ms after UNIX epoch" $ do
(parseUlidUtcSection "0000000014")
`shouldBe`
(Just $ timeGetDateTimeOfDay $ ElapsedP 0 36000000)

it "correctly parses a ULID string" $ do
let ulidText = "0000000014T4R3JR7HMQNREEW8" :: Text

(fmap show $ parseUlidText ulidText) `shouldBe` (Just ulidText)

describe "TaskLite" $ do
let
-- TODO: Make function more generic
Expand Down

0 comments on commit 258df47

Please sign in to comment.