Skip to content

Commit

Permalink
[kowainik#408] Fix escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
kukimik committed May 24, 2023
1 parent 37f1646 commit f64c08b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ The changelog is available [on GitHub][2].
Support GHC-9.4.4.
* Upgrade `mtl` and `validation-selective` upper boundary.
* Remove `transformers` dependency.
* [#408](https://github.com/kowainik/tomland/issues/412):
Fix escaping in printer.

## 1.3.3.2 – Oct 5, 2022

Expand Down
30 changes: 16 additions & 14 deletions src/Toml/Type/Printer.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ module Toml.Type.Printer

import GHC.Exts (sortWith)
import Data.Bifunctor (first)
import Data.Char (isAscii, ord)
import Data.Char (isAscii, isControl, ord)
import Data.Coerce (coerce)
import Data.Function (on)
import Data.HashMap.Strict (HashMap)
import Data.List (sortBy, foldl')
import Data.List (sortBy)
import Data.List.NonEmpty (NonEmpty)
import Data.Semigroup (stimes)
import Data.Text (Text)
Expand Down Expand Up @@ -182,19 +182,21 @@ prettyKeyValue options i = mapOrdered (\kv -> [kvText kv]) options . HashMap.toL

-- | Function encodes all non-ascii characters in TOML defined form using the isAscii function
showTextUnicode :: Text -> Text
showTextUnicode text = Text.pack $ show finalText
showTextUnicode t = Text.concat ["\"", Text.concatMap escape t, "\""]
where
xss = Text.unpack text
finalText = foldl' (\acc (ch, asciiCh) -> acc ++ getCh ch asciiCh) "" asciiArr

asciiArr = zip xss $ asciiStatus xss

getCh :: Char -> Bool -> String
getCh ch True = [ch] -- it is true ascii character
getCh ch False = printf "\\U%08x" (ord ch) :: String -- it is not true ascii character, it must be encoded

asciiStatus :: String -> [Bool]
asciiStatus = map isAscii
toCodepoint c = Text.pack $ printf "\\U%08x" (ord c)
escape :: Char -> Text
escape '\b' = "\\b"
escape '\t' = "\\t"
escape '\n' = "\\n"
escape '\f' = "\\f"
escape '\r' = "\\r"
escape '"' = "\\\""
escape '\\' = "\\\\"
escape c
| isControl c = toCodepoint c
| isAscii c = Text.singleton c
| otherwise = toCodepoint c

showDouble :: Double -> Text
showDouble d | isInfinite d && d < 0 = "-inf"
Expand Down

0 comments on commit f64c08b

Please sign in to comment.