Skip to content

Commit 3030780

Browse files
TheInnerLightad-si
authored andcommitted
Fix lexicographic ordering when timestamps are the same
1 parent 6339c01 commit 3030780

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

src/Data/ULID.hs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,7 @@ data ULID = ULID
6363
{ timeStamp :: !ULIDTimeStamp
6464
, random :: !ULIDRandom
6565
}
66-
deriving (Eq, Typeable, Data, Generic)
67-
68-
instance Ord ULID where
69-
compare (ULID ts1 _) (ULID ts2 _) = compare ts1 ts2
66+
deriving (Eq, Ord, Typeable, Data, Generic)
7067

7168
instance Show ULID where
7269
show (ULID ts bytes) = show ts ++ show bytes

src/Data/ULID/Random.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import qualified Data.ULID.Base32 as B32
2929

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

3434
instance Show ULIDRandom where
3535
show (ULIDRandom r) = T.unpack $ B32.encode 16 . roll . BS.unpack $ r

test/Data/ULIDSpec.hs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ import Data.Binary
66
import qualified Data.ByteString.Lazy as LBS
77
import Data.Char
88
import Data.Hashable
9-
import Data.List (nub, sort)
9+
import Data.List (nub, sort, sortOn)
1010
import qualified System.Random as R
1111

1212
import Data.ULID
1313

1414
import Test.Hspec
15+
import Data.ULID.TimeStamp (getULIDTimeStamp)
16+
import Data.ULID.Random (getULIDRandom)
1517

1618

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

39+
-- it should be lexicographically sortable even if the timestamps are the same
40+
ts <- getULIDTimeStamp
41+
ur1 <- getULIDRandom
42+
ur2 <- getULIDRandom
43+
ur3 <- getULIDRandom
44+
ur4 <- getULIDRandom
45+
46+
let u5 = ULID ts ur1
47+
let u6 = ULID ts ur2
48+
let u7 = ULID ts ur3
49+
let u8 = ULID ts ur4
50+
51+
sort [u5, u6, u7, u8] `shouldBe` sortOn show [u5, u6, u7, u8]
52+
3753
-- make sure it works in internal representation too :)
3854
let ul = [u3, u2, u4, u1]
3955
let ul' = sort ul

0 commit comments

Comments
 (0)