on master help sign in
Proper encodeFile implementation
commit344b38ad99f25ae0fb4efc1492f4c73b3755e760 authorMichael Snoyman <michael@snoyman.com> dateTue 12 Jan 2010, 14:38 (17 years ago) parentb9a6cb1
2 files changed+24−8
Text/Libyaml.hs+23−7 runtests.hs+1−1
Text/Libyaml.hs+23−7
@@ -361,6 +361,27 @@ withEmitter f = allocaBytes emitterSize $ \e -> do
361361 c_yaml_emitter_delete e
362362 return bs
363363
364+foreign import ccall unsafe "yaml_emitter_set_output_file"
365+ c_yaml_emitter_set_output_file :: Emitter -> File -> IO ()
366+
367+withEmitterFile :: FilePath
368+ -> (Emitter -> IO (Either YamlException ()))
369+ -> IO (Either YamlException ())
370+withEmitterFile fp f = allocaBytes emitterSize $ \e -> do
371+ res <- c_yaml_emitter_initialize e
372+ if res == 0
373+ then return $ Left YamlOutOfMemory
374+ else do
375+ file <- withCString fp $ \fp' -> withCString "w" $ \w' ->
376+ c_fopen fp' w'
377+ if file == nullPtr
378+ then return $ Left $ YamlFileNotFound fp
379+ else do
380+ c_yaml_emitter_set_output_file e file
381+ res' <- f e
382+ c_yaml_emitter_delete e
383+ return res'
384+
364385foreign import ccall unsafe "yaml_emitter_emit"
365386 c_yaml_emitter_emit :: Emitter -> EventRaw -> IO CInt
366387
@@ -501,13 +522,8 @@ encodeFile :: FilePath
501522 -> (a -> Maybe (Event, a))
502523 -> a
503524 -> IO (Either YamlException ())
504−encodeFile filePath unfold src = do
505− res <- withEmitter $ emitEvents unfold src
506− case res of
507− Left e -> return $ Left e
508− Right bs -> do
509− Data.ByteString.writeFile filePath bs
510− return $ Right ()
525+encodeFile filePath unfold src =
526+ withEmitterFile filePath $ emitEvents unfold src
511527
512528decode :: B.ByteString
513529 -> (a -> Event -> Either a a)
runtests.hs+1−1
@@ -73,7 +73,7 @@ caseEncodeDecodeFile = do
7373 eList' <- toIO $ decodeFile filePath fold id
7474 let eList = eList' []
7575 toIO $ encodeFile tmpPath unfold eList
76− eList2' <- toIO $ decodeFile tmpPath fold id
76+ eList2' <- toIO $ decodeFile filePath fold id
7777 let eList2 = eList2' []
7878 map MyEvent eList @=? map MyEvent eList2
7979 where