Skip to content

Commit ce67e4d

Browse files
committed
add Read instance for Unique
1 parent 79bce8c commit ce67e4d

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

external-stg-syntax/lib/Stg/Syntax.hs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import GHC.Generics
1111
import qualified Data.ByteString as BS
1212
import qualified Data.ByteString.Char8 as BS8
1313
import Data.Binary
14+
import Data.List
1415

1516
-- utility
1617

@@ -68,11 +69,26 @@ data Unique
6869
= Unique !Char !Int
6970
deriving (Eq, Ord, Generic)
7071

72+
instance Read Unique where
73+
readsPrec _d r =
74+
[ (Unique c (base62ToInt numStr), s)
75+
| (c : numStr, s) <- lex r
76+
]
77+
7178
instance Show Unique where
72-
show (Unique c n) = c : iToBase62 n
79+
show (Unique c n) = c : intToBase62 n
80+
81+
base62ToInt :: String -> Int
82+
base62ToInt numStr = sum
83+
[ 62^e * i
84+
| (e, n) <- zip ([0..] :: [Int]) $ reverse numStr
85+
, Just i <- [elemIndex n chars62]
86+
]
87+
where
88+
chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
7389

74-
iToBase62 :: Int -> String
75-
iToBase62 n_ = go n_ "" where
90+
intToBase62 :: Int -> String
91+
intToBase62 n_ = go n_ "" where
7692
go n cs | n < 62
7793
= let c = chooseChar62 n in c : cs
7894
| otherwise

0 commit comments

Comments
 (0)