Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added basic decoding from file

  • Loading branch information...
commit 22ced4da973f15537a82fa3da7d30e027e214ac0 1 parent 4a7cc88
Michael Snoyman authored
7 Data/Object/Yaml.hs
View
@@ -10,6 +10,8 @@ module Data.Object.Yaml
YamlDoc (..)
, readYamlDoc
, writeYamlDoc
+ -- * Reading directly from files
+ , readYamlObject
-- * 'YamlObject' definition
, YamlScalar (..)
, Tag (..)
@@ -65,6 +67,11 @@ readYamlDoc = fmap YamlDoc . B.readFile
writeYamlDoc :: FilePath -> YamlDoc -> IO ()
writeYamlDoc fp = B.writeFile fp . unYamlDoc
+readYamlObject :: FilePath -> IO (Object YamlScalar YamlScalar)
+readYamlObject fp = do
+ es <- join $ decodeFile fp
+ convertAttemptWrap es
+
data YamlScalar = YamlScalar
{ value :: ByteString
, tag :: Tag
1  Data/Object/Yaml/Internal.hs
View
@@ -86,5 +86,6 @@ data YamlException =
| YamlPrematureEventStreamEnd
| YamlNonScalarKey
| YamlInvalidStartingEvent Event
+ | YamlFileNotFound FilePath
deriving (Show, Typeable)
instance Exception YamlException
37 Data/Object/Yaml/Lib.hs
View
@@ -12,6 +12,7 @@ module Data.Object.Yaml.Lib
-- * Higher level functions
, encode
, decode
+ , decodeFile
) where
import qualified Data.ByteString.Internal as B
@@ -53,6 +54,37 @@ foreign import ccall unsafe "yaml_parser_set_input_string"
-> CULong
-> IO ()
+foreign import ccall unsafe "yaml_parser_set_input_file"
+ c_yaml_parser_set_input_file :: Parser
+ -> File
+ -> IO ()
+
+data FileStruct
+type File = Ptr FileStruct
+
+foreign import ccall unsafe "fopen"
+ c_fopen :: Ptr CChar
+ -> Ptr CChar
+ -> IO File
+
+foreign import ccall unsafe "fclose"
+ c_fclose :: File
+ -> IO ()
+
+withFileParser :: FilePath -> (Parser -> IO a) -> IO a
+withFileParser fp f = allocaBytes parserSize $ \p ->
+ do
+ res <- c_yaml_parser_initialize p
+ when (res == 0) $ throwIO YamlOutOfMemory
+ file <- withCString fp $ \fp' -> withCString "r" $ \r' ->
+ c_fopen fp' r'
+ when (file == nullPtr) $ throwIO $ YamlFileNotFound fp
+ c_yaml_parser_set_input_file p file
+ ret <- f p
+ c_fclose file
+ c_yaml_parser_delete p
+ return ret
+
withParser :: B.ByteString -> (Parser -> IO a) -> IO a
withParser bs f = allocaBytes parserSize $ \p ->
do
@@ -399,3 +431,8 @@ decode :: MonadFailure YamlException m
=> B.ByteString
-> IO (m [Event])
decode bs = withParser bs parserParse
+
+decodeFile :: MonadFailure YamlException m
+ => FilePath
+ -> IO (m [Event])
+decodeFile fp = withFileParser fp parserParse
7 c/helper.c
View
@@ -107,3 +107,10 @@ int get_scalar_style(yaml_event_t *e)
{
return e->data.scalar.style;
}
+
+int yaml_parser_set_input_filename(yaml_parser_t *parser, const char *filename)
+{
+ FILE *in = fopen(filename, "r");
+ if (!in) return 0;
+ yaml_parser_set_input_file(parser, in);
+}
Please sign in to comment.
Something went wrong with that request. Please try again.