Skip to content

Commit

Permalink
fix splitOn when sep appears at end (digital-asset#5872)
Browse files Browse the repository at this point in the history
Fixes digital-asset#5786.

CHANGELOG_BEGIN
[DAML Standard Lib] ``DA.Text.splitOn`` will now correctly handle the
case where the separator appears at the end but should not be matched,
as in ``splitOn "aa" "aaa" == ["", "a"]`` (previously this was
erroneously returning ``["", "a", ""]``). See digital-asset#5786 for more details.
CHANGELOG_END
  • Loading branch information
garyverhaegen-da authored May 7, 2020
1 parent 17f4dc2 commit e582e61
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
14 changes: 10 additions & 4 deletions compiler/damlc/daml-stdlib-src/DA/Text.daml
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,20 @@ dropWhile p = implode . P.dropWhile p . explode
dropWhileEnd : (Text -> Bool) -> Text -> Text
dropWhileEnd p = implode . L.dropWhileEnd p . explode

-- Separate function because recursion is only allowed at the top-level and we
-- don't want to pay for many implode/explode operations.
-- This shoud not be exported.
splitOnHelper : [Text] -> [Text] -> [Text]
splitOnHelper s t =
case L.stripInfix s t of
None -> [implode t]
Some (before, after) -> implode before :: splitOnHelper s after

-- | Break a text into pieces separated by the first text argument
-- (which cannot be empty), consuming the delimiter.
splitOn : Text -> Text -> [Text]
splitOn "" t' = [t']
splitOn _ "" = [""]
splitOn (explode -> s) (explode -> t) =
let fixit = if L.isSuffixOf s t then (++ [""]) else identity
in fixit $ implode <$> L.repeatedly (fmap (L.dropPrefix s) . L.breakOn s) t
splitOn s t = splitOnHelper (explode s) (explode t)

-- | Split a text before a given position so that for `0 <= n <= length t`,
-- `length (fst (splitAt n t)) == n`.
Expand Down
4 changes: 4 additions & 0 deletions compiler/damlc/tests/daml-test-files/Text.daml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ testSplitOn = scenario do
[""] === T.splitOn "" ""
["", "", ""] === T.splitOn "." ".."
["1", "2", ",3"] === T.splitOn ",," "1,,2,,,3"
["", "a"] === T.splitOn "aa" "aaa"
["", ""] === T.splitOn "aa" "aa"
["", "a"] === T.splitOn "aa" "aaa"
["", "", ""] === T.splitOn "aa" "aaaa"

testSplitAt = scenario do
("", "test") === T.splitAt 0 "test"
Expand Down

0 comments on commit e582e61

Please sign in to comment.