on master help sign in
Round tripping of special strings #31
commit2d71dd24d056e547fb24e979533b94df4f4edf22 authorMichael Snoyman <michael@snoyman.com> dateMon 7 Oct 2013, 15:18 (13 years ago) parent69dd574
2 files changed+19−1
Data/Yaml.hs+13−1 test/main.hs+6
Data/Yaml.hs+13−1
@@ -86,6 +86,7 @@ import Data.Text.Encoding.Error (lenientDecode)
8686import qualified Data.HashMap.Strict as M
8787import Data.Typeable
8888import Data.Attoparsec.Number
89+import qualified Data.HashSet as HashSet
8990
9091encode :: ToJSON a => a -> ByteString
9192encode obj = unsafePerformIO $
@@ -123,7 +124,13 @@ objToEvents' (Object pairs) rest =
123124-- https://github.com/snoyberg/yaml/issues/24
124125objToEvents' (String "") rest = EventScalar "" NoTag SingleQuoted Nothing : rest
125126
126−objToEvents' (String s) rest = EventScalar (encodeUtf8 s) StrTag PlainNoTag Nothing : rest
127+objToEvents' (String s) rest =
128+ event : rest
129+ where
130+ event
131+ -- Make sure that special strings are encoded as strings properly.
132+ | s `HashSet.member` specialStrings = EventScalar (encodeUtf8 s) StrTag SingleQuoted Nothing
133+ | otherwise = EventScalar (encodeUtf8 s) StrTag PlainNoTag Nothing
127134objToEvents' Null rest = EventScalar "null" NullTag PlainNoTag Nothing : rest
128135objToEvents' (Bool True) rest = EventScalar "true" BoolTag PlainNoTag Nothing : rest
129136objToEvents' (Bool False) rest = EventScalar "false" BoolTag PlainNoTag Nothing : rest
@@ -134,6 +141,11 @@ pairToEvents (k, v) rest =
134141 EventScalar (encodeUtf8 k) StrTag PlainNoTag Nothing
135142 : objToEvents' v rest
136143
144+-- | Strings which must be escaped so as not to be treated as non-string scalars.
145+specialStrings :: HashSet.HashSet Text
146+specialStrings = HashSet.fromList $ T.words
147+ "y Y yes Yes YES n N no No NO true True TRUE false False FALSE on On ON off Off OFF null Null NULL ~"
148+
137149-- Parsing
138150
139151data ParseException = NonScalarKey
test/main.hs+6
@@ -116,6 +116,12 @@ main = hspec $ do
116116 , hash = HM.fromList [("key1", "value1"), ("key2", "value2")]
117117 }
118118
119+ describe "round-tripping of special scalars" $ do
120+ let special = words "y Y On ON false"
121+ forM_ special $ \w -> it w $
122+ let v = object ["word" .= w]
123+ in D.decode (D.encode v) `shouldBe` Just v
124+
119125
120126
121127specialStrings :: [T.Text]