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

Fix lexicographic ordering when timestamps are the same #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 1 addition & 4 deletions src/Data/ULID.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,7 @@ data ULID = ULID
{ timeStamp :: !ULIDTimeStamp
, random :: !ULIDRandom
}
deriving (Eq, Typeable, Data, Generic)

instance Ord ULID where
compare (ULID ts1 _) (ULID ts2 _) = compare ts1 ts2
deriving (Eq, Ord, Typeable, Data, Generic)

instance Show ULID where
show (ULID ts bytes) = show ts ++ show bytes
Expand Down
2 changes: 1 addition & 1 deletion src/Data/ULID/Random.hs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import qualified Data.ULID.Base32 as B32

-- | Newtype wrapping a `ByteString`
newtype ULIDRandom = ULIDRandom BS.ByteString
deriving (Eq, Typeable, Data, Generic)
deriving (Eq, Ord, Typeable, Data, Generic)

instance Show ULIDRandom where
show (ULIDRandom r) = T.unpack $ B32.encode 16 . roll . BS.unpack $ r
Expand Down
18 changes: 17 additions & 1 deletion test/Data/ULIDSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import Data.Binary
import qualified Data.ByteString.Lazy as LBS
import Data.Char
import Data.Hashable
import Data.List (nub, sort)
import Data.List (nub, sort, sortOn)
import qualified System.Random as R

import Data.ULID

import Test.Hspec
import Data.ULID.TimeStamp (getULIDTimeStamp)
import Data.ULID.Random (getULIDRandom)


spec :: Spec
Expand All @@ -34,6 +36,20 @@ spec = do
let l' = sort l
l' `shouldBe` [show u1, show u2, show u3, show u4]

-- it should be lexicographically sortable even if the timestamps are the same
ts <- getULIDTimeStamp
ur1 <- getULIDRandom
ur2 <- getULIDRandom
ur3 <- getULIDRandom
ur4 <- getULIDRandom

let u5 = ULID ts ur1
let u6 = ULID ts ur2
let u7 = ULID ts ur3
let u8 = ULID ts ur4

sort [u5, u6, u7, u8] `shouldBe` sortOn show [u5, u6, u7, u8]

-- make sure it works in internal representation too :)
let ul = [u3, u2, u4, u1]
let ul' = sort ul
Expand Down