Skip to content
This repository was archived by the owner on Jul 19, 2025. It is now read-only.

Commit 06d6820

Browse files
committed
Handle empty Set in rndSetItem
1 parent e5fc740 commit 06d6820

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

src/Fake.hs

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -184,16 +184,23 @@ rndListItem xs = do
184184
pure . Just $ xs !! idx
185185

186186

187-
rndSetItem :: (RandomGen g, MonadState g m) => Set.Set a -> m a
188-
rndSetItem xs = do
189-
idx <- State.state $ randomR (0, Set.size xs - 1)
190-
pure $ Set.elemAt idx xs
187+
rndSetItem :: (RandomGen g, MonadState g m) => Set.Set a -> m (Maybe a)
188+
rndSetItem xs
189+
| Set.null xs = pure Nothing
190+
| otherwise = do
191+
idx <- State.state $ randomR (0, Set.size xs - 1)
192+
pure . Just $ Set.elemAt idx xs
191193

192194

193195
allPossibleChars :: Set.Set Char
194196
allPossibleChars = Set.fromList [minBound..maxBound]
195197

196198

199+
maybeMErr :: MonadError b m => b -> Maybe a -> m a
200+
maybeMErr err Nothing = Except.throwError err
201+
maybeMErr _ (Just x) = pure x
202+
203+
197204
-- | Create random data that would be matched by the given regex
198205
--
199206
-- >>> exec "fromRegex('\\d-\\d{1,3}-FOO')"
@@ -229,18 +236,18 @@ fromRegex input =
229236
(R.PBound lower mUpper pattern) -> do
230237
replicatePattern lower (fromMaybe defaultUpper mUpper) pattern
231238
(R.PAny _ patternSet) -> fromPatternSet patternSet
232-
(R.PAnyNot _ ps@(R.PatternSet mChars _ _ _)) -> case mChars of
233-
(Just notAllowedChars) ->
234-
charToText <$> rndSetItem (Set.difference allPossibleChars notAllowedChars)
235-
Nothing -> Except.throwError $ "Can't generate data from regex pattern" <> show ps
239+
(R.PAnyNot _ ps@(R.PatternSet mChars _ _ _)) -> do
240+
rndSetItem (maybe Set.empty (Set.difference allPossibleChars) mChars)
241+
>>= maybeMErr ("Can't generate data from regex pattern" <> show ps)
242+
<&> charToText
236243
(R.PEscape _ 'd') -> do
237244
T.pack . show <$> (State.state $ randomR (0, 9 :: Int))
238245
(R.PChar _ char) -> pure $ charToText char
239246
_ -> Except.throwError $ "Can't generate data from regex pattern" <> show p
240-
fromPatternSet ps@(R.PatternSet mCharSet _ _ _) =
241-
case mCharSet of
242-
(Just charSet) -> charToText <$> rndSetItem charSet
243-
Nothing -> Except.throwError $ "Can't generate data from regex pattern" <> show ps
247+
fromPatternSet ps@(R.PatternSet mCharSet _ _ _) = do
248+
rndSetItem (fromMaybe Set.empty mCharSet)
249+
>>= maybeMErr ("Can't generate data from regex pattern" <> show ps)
250+
<&> charToText
244251
charToText c = T.pack [c]
245252

246253

0 commit comments

Comments
 (0)