packages feed

RefSerialize (empty) → 0.2

raw patch · 20 files changed

+1065/−0 lines, 20 filesdep +basedep +containerssetup-changedbinary-added

Dependencies added: base, containers

Files

+ Data/Parser.hs view
@@ -0,0 +1,426 @@+module Data.Parser( ST(..),(<?>),(<|>),char,anyChar, string, upper, space, digit+                 , sepBy, between, choice, option, notFollowedBy, many+                 , bool++                 , charLiteral      -- :: ST Char+                 , stringLiteral    -- :: ST String+                 , natural          -- :: ST Integer+                 , integer          -- :: ST Integer+                 , float            -- :: ST Double+                 , naturalOrFloat   -- :: ST (Either Integer Double)+                 , decimal          -- :: ST Integer+                 , hexadecimal      -- :: ST Integer+                 , octal            -- :: ST Integer+            +                 , symbol           -- :: String -> ST String+                 , lexeme           -- :: forall a. ST a -> ST a+                 , whiteSpace       -- :: ST ()     +              +                 , parens           -- :: forall a. ST a -> ST a +                 , braces           -- :: forall a. ST a -> ST a+                 , angles           -- :: forall a. ST a -> ST a+                 , brackets         -- :: forall a. ST a -> ST a+                 -- "squares" is deprecated++                 , semi             -- :: ST String+                 , comma            -- :: ST String+                 , colon            -- :: ST String+                 , dot              -- :: ST String+                 , semiSep          -- :: forall a . ST a -> ST [a]+                 , semiSep1         -- :: forall a . ST a -> ST [a]+                 , commaSep         -- :: forall a . ST a -> ST [a]+                 , commaSep1        -- :: forall a . ST a -> ST [a]                +                    +                 +                 +                 ) where++import Control.Monad+import Data.Char(isUpper,isSpace,digitToInt)+import qualified Data.Map as M+import Data.Serialize+++data ST a= ST(Stat-> Either Error (Stat , a) ) ++--monadic serialization/deserialization+instance  Monad ST where+    return  x = ST (\s -> Right (s, x)) +    ST g >>= f = ST (\s ->+                      +                       case g s of+                        Right (s', x)->+                          let +                              ST fun  = f x +                          in  case  fun s' of+                               left@(Left msg) -> left+                               rigth->  rigth+                              +                        Left msg -> Left msg+                      +                    )+                    +instance MonadPlus ST where+  mzero= ST (\(Stat (a,b,c)) -> Left $ Error "an error occurred")+  mplus p1 p2   = parsecPlus p1 p2++infixr 1 <|>    +(<|>) = parsecPlus+infix  0 <?>++p <?> msg = label p msg++parsecPlus :: ST a -> ST a -> ST a+parsecPlus (ST p1) (ST p2)+    = ST (\state ->+        case (p1 state) of        +          Left (Error s) -> case (p2 state) of+                                 Left (Error s') -> Left $ Error ( s++ "\n"++ s')+                                 consumed-> consumed+          other             -> other+      )++++label :: ST a -> String -> ST a    +label p msg+  = labels p [msg]++labels :: ST a -> [String] -> ST a+labels (ST p) msgs+    = ST (\state -> +        case (p state) of+          Left(Error reply) -> Left $  Error ( reply ++concatMap ("\n in "++) msgs)+                           +          other       -> other+      )++char :: Char -> ST Char          +   +char c= ST(\(Stat(cs,s,v)) ->  +   if null s then Left (Error $ "unexpected end of input")+   else if c== head s then Right(Stat(cs,tail s,v), c) +   else Left (Error ( "char "++ c:" not match " ++ '\"':s++"\"" )))+   +                           +anyChar = ST(\(Stat(cs,s,v)) ->   +    if null s then Left (Error $ "unexpected end of input")+    else Right(Stat(cs,tail s,v), head s))++satisfy bf= ST(\(Stat(cs,s,v)) ->  let  heads= head s in+     if null s then Left (Error $ "unexpected end of input")+     else if bf heads then  Right(Stat(cs,tail s,v), heads)+     else Left (Error ( "satisfy  not matching condition in " ++ '\"':s++"\"" )))++                                         +upper = ST(\(Stat(cs,s,v)) ->  let  heads= head s in+     if null s then Left (Error $ "unexpected end of input")+     else if isUpper (head s) then  Right(Stat(cs,tail s,v), head s)+     else Left (Error ( "upper  not matching condition in " ++ '\"':s++"\"" )))++     +space =ST(\(Stat(cs,s,v)) ->  let  heads= head s in+     if null s then Left (Error $ "unexpected end of input")+     else if isSpace heads then Right(Stat(cs,tail s,v), heads) +     else Left (Error ( "expected space at the head of " ++ s )))+      +                                 +digit1 l1 l2= ST(\(Stat(cs,s,v)) -> let c= head s in  if c >= l1 && c <= l2  then Right(Stat(cs,tail s,v), c) +                                     else Left (Error ( "expected digit at the head of " ++ s )))+      +empty = ST(\(Stat(cs,s,v)) ->   if null s  then Right(Stat(cs, s,v), ()) +                                     else Left (Error ( "expected empty list" )))                               +                               +octDigit= digit1 '0' '7'++digit= digit1 '0' '9'++hexDigit= ST(\(Stat(cs,s,v)) ->  let c= head s in if c >= '0' && c <= '9'  || c >= 'a' && c<='f'  || c >= 'A' && c <= 'F'  then Right(Stat(cs,tail s,v), c) +                                     else Left (Error ( "expected space at the head of " ++ s )))+                               +oneOf xs= ST(\(Stat(cs,s,v)) -> let c= head s in if c `elem` xs then Right(Stat(cs,tail s,v), c) +                                     else Left (Error ( "expected digit at the head of " ++ s )))++noneOf xs= ST(\(Stat(cs,s,v)) -> let c= head s in if not $ c `elem` xs then Right(Stat(cs,tail s,v), c) +                                     else Left (Error ( "expected digit at the head of " ++ s )))++try p= p+                             +unexpected msg+    = ST (\state -> Left (Error $ msg++ "unexpected"))++sepBy1,sepBy :: ST a -> ST  sep -> ST  [a]+sepBy p sep         = sepBy1 p sep <|> return []+sepBy1 p sep        = do{ x <- p+                        ; xs <- many (sep >> p)+                        ; return (x:xs)+                        }+                        <?> "sepBy "+between open close p+                    = do{ open; x <- p; close; return x } +                   +choice ps           = foldr (<|>) mzero ps <?> "choice "++option x p          = p <|> return x +             +             +notFollowedBy p     = try (do{ c <- p; unexpected (show [c]) }+                           <|> return ()+                          )  ++                          <?> "notFollowedBy "++skipMany1 p         = do{ p; skipMany p }++skipMany p          = scan+                    where+                      scan  = do{ p; scan } <|> return ()                  +++manyTill p end      = scan+                    where+                      scan  = do{ end; return [] }+                            <|>+                              do{ x <- p; xs <- scan; return (x:xs) }+++string ""=  return ""              +string ys@(x:xs)= do +                  char x+                  string xs+                  return ys+                  <?> "string "++ys +++bool = lexeme ( do{ symbol "True" ; return True} <|> do{ symbol "False" ; return False})   <?> "Bool"++many :: ST a -> ST [a]+many p = many1 p <|> return []+many1 :: ST a -> ST [a]+many1 p = do {a <- p; as <- many p; return (a:as)}   +++--from Token.hs+    -----------------------------------------------------------+    -- Bracketing+    -----------------------------------------------------------+parens p        = between (symbol "(") (symbol ")") p <?> "parens "+braces p        = between (symbol "{") (symbol "}") p <?> "braces "+angles p        = between (symbol "<") (symbol ">") p <?> "angles "+brackets p      = between (symbol "[") (symbol "]") p <?> "brackets "++semi            = symbol ";" +comma           = symbol ","+dot             = symbol "."+colon           = symbol ":"++commaSep p      = sepBy p comma+semiSep p       = sepBy p semi++commaSep1 p     = sepBy1 p comma+semiSep1 p      = sepBy1 p semi+++-----------------------------------------------------------+-- Chars & Strings+-----------------------------------------------------------+-- charLiteral :: ST Char+charLiteral     = lexeme (between (char '\'') +                                (char '\'' <?> "end of character")+                                characterChar )+                <?> "character"++characterChar   = charLetter <|> charEscape +                <?> "literal character"++charEscape      = do{ char '\\'; escapeCode }+charLetter      = satisfy (\c -> (c /= '\'') && (c /= '\\') && (c > '\026'))++++-- stringLiteral :: ST String+stringLiteral   = lexeme (+                do{ str <- between (char '"')                   +                                        (char '"' <?> "end of string")+                                        (many stringChar) +                ; return (foldr (maybe id (:)) "" str)+                }+                <?> "literal string")++-- stringChar :: ST (Maybe Char)+stringChar      =   do{ c <- stringLetter; return (Just c) }+                <|> stringEscape +                <?> "string character"+        +stringLetter    = satisfy (\c -> (c /= '"') && (c /= '\\') && (c > '\026'))++stringEscape    = do{ char '\\'+                ;     do{ escapeGap  ; return Nothing }+                        <|> do{ escapeEmpty; return Nothing }+                        <|> do{ esc <- escapeCode; return (Just esc) }+                }+                +escapeEmpty     = char '&'+escapeGap       = do{ many1 space+                ; char '\\' <?> "end of string gap"+                }+                +                +                +-- escape codes+escapeCode      = charEsc <|> charNum <|> charAscii <|> charControl+                <?> "escape code"++-- charControl :: ST Char+charControl     = do{ char '^'+                ; code <- upper+                ; return (toEnum (fromEnum code - fromEnum 'A'))+                }++-- charNum :: ST Char                    +charNum         = do{ code <- decimal +                                <|> do{ char 'o'; number 8 octDigit }+                                <|> do{ char 'x'; number 16 hexDigit }+                ; return (toEnum (fromInteger code))+                }++charEsc         = choice (map parseEsc escMap)+                where+                parseEsc (c,code)     = do{ char c; return code }+                +charAscii       = choice (map parseAscii asciiMap)+                where+                parseAscii (asc,code) = try (do{ string asc; return code })+++-- escape code tables+escMap          = zip ("abfnrtv\\\"\'") ("\a\b\f\n\r\t\v\\\"\'")+asciiMap        = zip (ascii3codes ++ ascii2codes) (ascii3 ++ ascii2) ++ascii2codes     = ["BS","HT","LF","VT","FF","CR","SO","SI","EM",+                "FS","GS","RS","US","SP"]+ascii3codes     = ["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL",+                "DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB",+                "CAN","SUB","ESC","DEL"]++ascii2          = ['\BS','\HT','\LF','\VT','\FF','\CR','\SO','\SI',+                '\EM','\FS','\GS','\RS','\US','\SP']+ascii3          = ['\NUL','\SOH','\STX','\ETX','\EOT','\ENQ','\ACK',+                '\BEL','\DLE','\DC1','\DC2','\DC3','\DC4','\NAK',+                '\SYN','\ETB','\CAN','\SUB','\ESC','\DEL']+++-----------------------------------------------------------+-- Numbers+-----------------------------------------------------------+-- naturalOrFloat :: ST (Either Integer Double)+naturalOrFloat  = lexeme (natFloat) <?> "number"++float           = lexeme floating   <?> "float"+integer         = lexeme int        <?> "integer"+natural         = lexeme nat        <?> "natural"+++-- floats+floating        = do{ n <- decimal +                ; fractExponent n+                }+++natFloat        = do{ char '0'+                ; zeroNumFloat+                }+                <|> decimalFloat+                +zeroNumFloat    =  do{ n <- hexadecimal <|> octal+                        ; return (Left n)+                        }+                <|> decimalFloat+                <|> fractFloat 0+                <|> return (Left 0)                  +                +decimalFloat    = do{ n <- decimal+                ; option (Left n) +                                (fractFloat n)+                }++fractFloat n    = do{ f <- fractExponent n+                ; return (Right f)+                }+                +fractExponent n = do{ fract <- fraction+                ; expo  <- option 1.0 exponent'+                ; return ((fromInteger n + fract)*expo)+                }+                <|>+                do{ expo <- exponent'+                ; return ((fromInteger n)*expo)+                }++fraction        = do{ char '.'+                ; digits <- many1 digit <?> "fraction"+                ; return (foldr op 0.0 digits)+                }+                <?> "fraction"+                where+                op d f    = (f + fromIntegral (digitToInt d))/10.0+                +exponent'       = do{ oneOf "eE"+                ; f <- sign+                ; e <- decimal <?> "exponent"+                ; return (power (f e))+                }+                <?> "exponent"+                where+                power e  | e < 0      = 1.0/power(-e)+                        | otherwise  = fromInteger (10^e)+++-- integers and naturals+int             = do{ f <- lexeme sign+                ; n <- nat+                ; return (f n)+                }+                +-- sign            :: ST (Integer -> Integer)+sign            =   (char '-' >> return negate) +                <|> (char '+' >> return id)     +                <|> return id++nat             = zeroNumber <|> decimal++zeroNumber      = do{ char '0'+                ; hexadecimal <|> octal <|> decimal <|> return 0+                }+                <?> ""       ++decimal         = number 10 digit        +hexadecimal     = do{ oneOf "xX"; number 16 hexDigit }+octal           = do{ oneOf "oO"; number 8 octDigit  }+++    -- number :: Integer -> ST Char -> ST Integer+number base baseDigit+        = do{ digits <- many1 baseDigit+            ; let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits+            ; seq n (return n)+            }          ++    +    -----------------------------------------------------------+    -- White space & symbols+    -----------------------------------------------------------+symbol name+        = lexeme (string name)++lexeme p       +        = do{ x <- p; whiteSpace ; return x  }+      +      +    --whiteSpace    +whiteSpace  = skipMany (simpleSpace <?> "")+          +          +simpleSpace = skipMany1 (satisfy isSpace)    +        +
+ Data/RefSerialize.hs view
@@ -0,0 +1,203 @@+{-# OPTIONS -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances  #-}+module Data.RefSerialize +(   module Data.Parser  -- export the complete set of Parsec.Token parsers adapted for composing readp parsers+    ,Serialize(+        showp  -- :: c -> ST String  -- shows the content of a expression, must be user defined+   +       ,readp  -- ::  ST c           -- read the content of a expression, must be user defined++       ,rshowp -- :: c -> ST String  -- insert a reference (a variable in the where section) +       --rshowp -- = insertVar  showp -- default definition+   +       ,rreadp -- :: ST c            -- read a variable in the where section (to use for deserializing rshowp output)+       --rreadp -- = readVar  readp   -- default definition+    +    +    )+    ,rShow    -- ::  Serialize c => c -> String         -- use the rshowp parser to serialize the object+    ,rRead    -- ::  Serialize c => String ->c          -- deserialize  trough the rreadp parser+    ,insertVar-- :: (a -> ST String) -> a -> ST String  -- insert a variable, its value generated by a showp parser, will be inserted in the where section+    ,readVar  -- ::  read a variable referenced int the where section+    ,varName  -- ::  two variables that point to the same address will have identical varname (derived from import System.Mem.StableName)+    ,runR     -- :: ST a -> String ->  a    runR parser string  -- deserialize the string with the parser+    ,runW     -- :: ST String -> String     runW $ parser x     -- serialize x with the parser+)   + where+import qualified Data.Map as M+import Data.Serialize+import Data.Parser+import Unsafe.Coerce+import Data.Char(isAlpha, isSpace, isAlphaNum)+--import Token++class Serialize c where+   showp :: c -> ST String+   +   readp ::  ST c++   rshowp :: c -> ST String+   rshowp  = insertVar  showp+   +   rreadp :: ST c+   rreadp = readVar  readp +{-+#ifdef Axioms++   serializeAxioms: Axioms c+   serializeAxioms= axioms{+         unary=   [Axiom "reverse" +                            (\x ->  let str= rShow x+                                        y = rRead xtr+                                    in  y== x)+                                       +                   AxioM "pointer equality"+                           (\x ->   let str= rShow[x,x]+                                        [y,z] = rRead str+                                    in varName y== varName z)+                  ]+        }+#endif                                          +-}   ++         +rShow :: Serialize c => c -> String+rShow c= runW  $  rshowp c+    +rRead :: Serialize c => String ->c+rRead str= runR rreadp $ str+++readSR :: Read a => ST a+readSR = ST(\(Stat(c,s,v)) -> let ((x,str2):_)= readsPrec 1 s in Right(Stat(c,str2,v),x) )++runR:: ST a -> String ->  a+runR   (ST f) str= +    let (struct, vars)= readContext "where " str +    in  case   f (Stat(M.empty,struct,vars) ) of+          Right (Stat _, a) -> a+          Left (Error s) -> error s+  ++  +showSR :: Show a => a -> ST String+showSR var= ST(\(Stat(c,s,v)) ->  Right(Stat(c,s,v),show var))++runW :: ST String -> String+runW (ST f) = case  f (Stat(M.empty,"",""))  of+              Right (Stat (c,_,_), str) ->+                let scontext= M.assocs c+                    show1 c= concatMap (\(n,(_,v))->"v"++ show n++"= "++v++"; ")  scontext  +                    vars= show1  c+                    strContext= if null vars  then "" else  " where {"++vars ++ "}"+                    +                in  str ++ strContext+            +              Left (Error s) -> error s+      +++instance  Serialize a => Serialize [a] where+  showp []= return "[]"+  showp (x:xs)=  do+           s1<-   showp x+           sn<- mapM f xs+           return $ "["++ s1++ concat sn ++"]"+           where+           f x=do  str <- showp (x:: a)+                   return $ ", "++str+  ++  readp =  brackets $ commaSep $ readp ++  rshowp  = insertVar rshowp1 where+    rshowp1 []= insertVar return "[]"+    rshowp1 (x:xs)= do+           s1<-   rshowp x+           sn<- mapM f xs+           return $ "["++ s1++ concat sn ++"]"+           where+           f x= do str <- rshowp (x:: a)+                   return $ ", "++str+  ++  rreadp = readVar $ brackets $ commaSep $ rreadp   ++{-+instance Serialize Int where+  showp = showSR+  readp = readSR++instance Serialize Char where+  showp = showSR+  readp = readSR+-}+instance (Show a, Read a) => Serialize a where+    showp = showSR+    readp = readSR+                +{-      +instance Serialize String where+    showp = showSR +    readp = readSR +    +instance Serialize Integer where+    showp = showSR+    readp = readSR                  +-}++-- | insert a variable at this position. and the expression value in the where part.+--   runW rshowp (1::Int) -> "1"+--   runW (insertVar rshowp) (1::Int) -> v1 where { v1=1}+--   This is useful when the object is referenced many times++insertVar :: (a -> ST String) -> a -> ST String+insertVar parser x= ST(\(Stat(c,s,v))->+ let mf = trytofindEntireObject x c in+ case mf of+   Just  var ->  Right(Stat(c,s,v),var)+   Nothing -> +         let +            ST f= parser x+            Right (Stat (c',_,_), str) = f  (Stat(c,s,v))+            +         in Right(Stat(addc str c',s,v), ' ':varname))+ where+  addc str c= M.insert ( hash) (unsafeCoerce x,  str) c +  hash = hasht x+  varname= "v" ++ show hash ++  trytofindEntireObject x c= +         case M.lookup  hash  c  of+           Nothing -> Nothing+           Just _  -> Just varname+           + ++readVar :: Serialize c => ST c -> ST c+readVar parser=  ST(\(Stat(c,s,v))->+          let+               s1= dropWhile isSpace s+               (var, str2) = span isAlphaNum s1++          in case trytofindEntireObject (numVar var) c  of+ +           Just  (x,_) ->  Right(Stat(c,str2,v),unsafeCoerce x)+           Nothing ->              +            let   +               (_, rest)= readContext (var++"= ") v+               ST f= parser +            in  case f  (Stat(c,rest,v)) --`debug` ("s="++s++"var="++var++"rest="++rest )+            of+                 Right (Stat(c',s',v'),x) ->+                   let c''= M.insert (numVar var) (unsafeCoerce x,  "") c' +                   in  Right (Stat(c'',str2,v),x)  +                   +                 err -> err)+  where+  trytofindEntireObject x c= +         case M.lookup   x  c  of+           Nothing -> Nothing+           justx   -> justx+++
+ Data/Serialize.hs view
@@ -0,0 +1,48 @@+{-# OPTIONS -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances  #-}+module Data.Serialize where+import GHC.Prim+import GHC.Exts+import Unsafe.Coerce+import Data.List(isPrefixOf,insertBy,elem)+import Data.Char(isAlpha,isAlphaNum,isSpace,isUpper)+import qualified Data.Map as M+import System.Mem.StableName+import System.IO.Unsafe+import Control.Monad (MonadPlus(..))++import Debug.Trace++debug a b= trace b a++++type MFun=  Char -- usafeCoherced to char to store simply the address of the function+type VarName = String+type ShowF= String+type Context =  M.Map Int (MFun,ShowF)++data Error= Error String+data Stat= Stat (Context, String, String)++++readContext pattern str= readContext1 "" str where+ readContext1 s str| null str = (s,"")+                   | pattern `isPrefixOf` str = (s,drop n str)+                   | otherwise=   readContext1 (s++[head str]) (tail str)+                    where n= length pattern++++hasht x=  (hashStableName . unsafePerformIO . makeStableName) x+ +varName x= "v"++ (show . hasht) x+++++numVar :: String -> Int+numVar var= read $ tail var++  +
+ LICENSE view
@@ -0,0 +1,27 @@+Copyright (c) Alberto Gómez Corona 2008 agocorona@gmail.com++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:+1. Redistributions of source code must retain the above copyright+   notice, this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright+   notice, this list of conditions and the following disclaimer in the+   documentation and/or other materials provided with the distribution.+3. Neither the name of the author nor the names of his contributors+   may be used to endorse or promote products derived from this software+   without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF+SUCH DAMAGE.
+ RefSerialize.cabal view
@@ -0,0 +1,40 @@+name:                RefSerialize+version:             0.2+synopsis:            Write to and read from Strings maintaining internal memory references +description:         +                     Read, Show and Data.Binary do not check for pointers to the same address +                     as a result, the data is duplicated when serialized. This is a waste of space in the filesystem +                     and  also a waste of serialization time. but the worst consequence is that, when the serialized data is read,+                     it allocates multiple copies for the same object referenced multiple times. Because multiple referenced+                     data is very typical in a pure language such is Haskell, this means that the resulting data loose the beatiful +                     economy of space and processing time that referential transparency permits.+                     +                     This package allows the serialization and deserialization of large data structures without duplication of data, with+                     the result of optimized performance and memory usage. It is also useful for debugging purposes.+                     +                     There are automatic derived instances for instances of Read/Show, lists and strings. the deserializer+                     contains a subset of Parsec.Token for deserialization. +                     +                     Every instance of Show/Read is also a instance of Data.RefSerialize+                     +                     the serialized string has the form "expr( var1, ...varn) where  var1=value1,..valn=valueN " so that the+                     string can ve EVALuated.+                     +                     See demo.hs and tutorial. I presumably will add a entry in haskell-web.blogspot.com+                     +                     To develop: -derived instances for Data.Binary+                                 -serialization to/from ByteStings+                     
++category:            Parsing+license:             BSD3+license-file:        LICENSE+author:              Alberto Gómez Corona+maintainer:          agocorona@gmail.com+Tested-With:         GHC == 6.8.2+Build-Type:          Simple+build-Depends:       base,containers+Cabal-Version:       >= 1.2++exposed-modules:     Data.RefSerialize+ghc-options:         
+ Setup.lhs view
@@ -0,0 +1,5 @@+#! /usr/bin/runghc
+
+> import Distribution.Simple
+>
+> main = defaultMain
+ demo.hs view
@@ -0,0 +1,132 @@+module Main where++import System.Mem.StableName+import System.IO.Unsafe+import Data.RefSerialize++--simple data structure+data S= S Int Int deriving ( Show, Eq)         +++instance  Serialize S  where+    showp (S x y)= do+                    xs <- rshowp x  -- rshowp parsers can be inside showp parser+                    ys <- rshowp y+                    return $ "S "++xs++" "++ys+       +     +    readp =  do+                    symbol "S"+                    x <- rreadp    +                    y <- rreadp+                    return $ S x y++----------------- a more complex structure with mixed record and array with default read/show type serialization ----++data Data = Data Int String deriving (Read,Show)++data Stat a= Workflows [String]+           | Stat{ wfName :: String, state:: Int, index :: Int, recover:: Bool, sync :: Bool , resource :: [a]} +           | I a+           deriving (Read,Show)  ++-- the parser definitions for this structure++instance Serialize a =>  Serialize (Stat a) where+    showp (Workflows list)= do  +          str <- showp list+          return $ "StatWorkflows "++ str+    showp (I x) = return $ "I " ++ rShow x +    showp  (Stat wfName state index recover sync resource)= do+       parsea <- rshowp resource   --creates a variable +       return $ "Stat "++ show wfName ++" "++ show state++" "++show index++" "++show recover++" "++ show sync ++ parsea  +       +    readp = choice [rStat, rData, rWorkflows] where --choice is a exported parser (Parsec.Token interface is included) +        rStat= do+              symbol "Stat" +              wfName <- stringLiteral    -- various parsec parsers are used+              state <- integer+              index <- integer+              recover <- bool+              sync <- bool+              resource <- rreadp   -- read the variable +              return $ Stat wfName (fromIntegral state) (fromIntegral index) recover sync resource +              +        rData= do+               symbol "I"+               a <- readp+               return $ I a ++        rWorkflows= do+               symbol "StatWorkflows"+               list <- readp+               return $ Workflows list  ++          +main=  do+   let x = (5 :: Int)+   putStrLn $ runW $ showp $ S x x+   let xss = [[x,x],[x,x]]+   let str= rShow xss+   putStrLn str+   let y = rRead  " v10 where {v6= [ v8, v8]; v8= 5; v9= [v8, v8]; v10= [ v6,  v9]; }" ::[[Int]]+   print y +   putStrLn "instance (Show a, Read a) => Serialize a "+   putStr "rShow 10="+   putStrLn $ rShow (10 :: Int)+   +   putStrLn "serialize String's"+   let x= "hello"+   let str= rShow x+   putStrLn $ "rShow "++ str++"= "++str+  +   let y= rRead str :: String+   print y+   print $ x==y++   putStrLn "serialize [a] "    +   let xs= take 2 $ repeat (Data 0 "")+   +   let xss= take 2 $ repeat xs+   let str= rShow xss+   putStrLn str+   let x= rRead str :: [[Data]]++++   let x= 1 :: Int+   let xs= take 5 $ repeat x++   print xs+   putStr "rShow xs="+   let str= rShow  xs +   putStrLn str++   +   putStrLn "using the RefSerialize instance of Stat (see definition in this file)" +   let stat0 = Stat{ wfName="", state=0, index=0, recover=False, resource=[], sync= True} ++   let data0= Data 0 ""++   let str = rShow  stat0{resource= (take 2 $ repeat  data0) ++ (take 2 $ repeat (Data 1 "1")) }+   putStrLn "references to the same address are identified by rshowp. they point to the same variable in the serialized data"+   putStrLn $ "rShow "++ show data0 ++"= "++ str+   let stat1= rRead str :: Stat Data+   +   putStrLn "data that point to the same variable when serializeds point to the same memory address when deserialized"+   +   let addr x= (hashStableName . unsafePerformIO . makeStableName) x+   let x= (resource stat1 !! 0)+   putStr "first element of the resource list= " +   print x+   putStr "address of this element= "+   print $ addr x+   let y= (resource stat1 !! 1)+   putStr "second element of the resource list= "+   print y+   putStr "address of this element= "+   print $ addr y+   print $ addr y== addr x+     + +
+ dist/build/Data/Parser.hi view

binary file changed (absent → 26899 bytes)

+ dist/build/Data/Parser.o view

binary file changed (absent → 151984 bytes)

+ dist/build/Data/RefSerialize.hi view

binary file changed (absent → 9377 bytes)

+ dist/build/Data/RefSerialize.o view

binary file changed (absent → 30996 bytes)

+ dist/build/Data/Serialize.hi view

binary file changed (absent → 2987 bytes)

+ dist/build/Data/Serialize.o view

binary file changed (absent → 7088 bytes)

+ dist/build/HSRefSerialize-0.2.o view

binary file changed (absent → 26505 bytes)

+ dist/build/autogen/Paths_RefSerialize.hs view
@@ -0,0 +1,29 @@+module Paths_RefSerialize (+    version,+    getBinDir, getLibDir, getDataDir, getLibexecDir,+    getDataFileName+  ) where++import Data.Version (Version(..))+import System.Environment (getEnv)++version :: Version+version = Version {versionBranch = [0,2], versionTags = []}++bindir, libdir, datadir, libexecdir :: FilePath++bindir     = "/usr/local/bin"+libdir     = "/usr/local/lib/RefSerialize-0.2/ghc-6.8.2"+datadir    = "/usr/local/share/RefSerialize-0.2"+libexecdir = "/usr/local/libexec"++getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath+getBinDir = catch (getEnv "RefSerialize_bindir") (\_ -> return bindir)+getLibDir = catch (getEnv "RefSerialize_libdir") (\_ -> return libdir)+getDataDir = catch (getEnv "RefSerialize_datadir") (\_ -> return datadir)+getLibexecDir = catch (getEnv "RefSerialize_libexecdir") (\_ -> return libexecdir)++getDataFileName :: FilePath -> IO FilePath+getDataFileName name = do+  dir <- getDataDir+  return (dir ++ "/" ++ name)
+ dist/build/autogen/cabal_macros.h view
@@ -0,0 +1,14 @@+/* DO NOT EDIT: This file is automatically generated by Cabal */++/* package base-3.0.1.0 */+#define MIN_VERSION_base(major1,major2,minor) \+  (major1) <  3 || \+  (major1) == 3 && (major2) <  0 || \+  (major1) == 3 && (major2) == 0 && (minor) <= 1++/* package containers-0.1.0.1 */+#define MIN_VERSION_containers(major1,major2,minor) \+  (major1) <  0 || \+  (major1) == 0 && (major2) <  1 || \+  (major1) == 0 && (major2) == 1 && (minor) <= 0+
+ dist/build/libHSRefSerialize-0.2.a view

binary file changed (absent → 35790 bytes)

+ dist/installed-pkg-config view
@@ -0,0 +1,44 @@+name: RefSerialize+version: 0.2+license: BSD3+copyright:+maintainer: agocorona@gmail.com+stability:+homepage:+package-url:+description: Read, Show and Data.Binary do not check for pointers to the same address+             as a result, the data is duplicated when serialized. This is a waste of space in the filesystem+             and  also a waste of serialization time. but the worst consequence is that, when the serialized data is read,+             it allocates multiple copies for the same object referenced multiple times. Because multiple referenced+             data is very typical in a pure language such is Haskell, this means that the resulting data loose the beatiful+             economy of space and processing time that referential transparency permits.+             This package allows the serialization and deserialization of large data structures without duplication of data, with+             the result of optimized performance and memory usage. It is also useful for debugging purposes.+             There are automatic derived instances for instances of Read/Show, lists and strings. the deserializer+             contains a subset of Parsec.Token for deserialization.+             Every instance of Show/Read is also a instance of Data.RefSerialize+             the serialized string has the form "expr( var1, ...varn) where  var1=value1,..valn=valueN " so that the+             string can ve EVALuated.+             See demo.hs and tutorial. I presumably will add a entry in haskell-web.blogspot.com+             To develop: -derived instances for Data.Binary+             -serialization to/from ByteStings+category: Middleware+author: Alberto Gómez Corona+exposed: True+exposed-modules: Data.RefSerialize+hidden-modules:+import-dirs: /usr/local/lib/RefSerialize-0.2/ghc-6.8.2+library-dirs: /usr/local/lib/RefSerialize-0.2/ghc-6.8.2+hs-libraries: HSRefSerialize-0.2+extra-libraries:+extra-ghci-libraries:+include-dirs:+includes:+depends: base-3.0.1.0 containers-0.1.0.1+hugs-options:+cc-options:+ld-options:+framework-dirs:+frameworks:+haddock-interfaces: /usr/local/share/doc/RefSerialize-0.2/html/RefSerialize.haddock+haddock-html: /usr/local/share/doc/RefSerialize-0.2/html
+ dist/setup-config view
@@ -0,0 +1,2 @@+Saved package config for RefSerialize-0.2 written by Cabal-1.6.0.1 using ghc-6.8+LocalBuildInfo {installDirTemplates = InstallDirs {prefix = "/usr/local", bindir = "$prefix/bin", libdir = "$prefix/lib", libsubdir = "$pkgid/$compiler", dynlibdir = "$libdir", libexecdir = "$prefix/libexec", progdir = "$libdir/hugs/programs", includedir = "$libdir/$libsubdir/include", datadir = "$prefix/share", datasubdir = "$pkgid", docdir = "$datadir/doc/$pkgid", mandir = "$datadir/man", htmldir = "$docdir/html", haddockdir = "$htmldir"}, compiler = Compiler {compilerId = CompilerId GHC (Version {versionBranch = [6,8,2], versionTags = []}), compilerExtensions = [(CPP,"-XCPP"),(PatternGuards,"-XPatternGuards"),(UnicodeSyntax,"-XUnicodeSyntax"),(MagicHash,"-XMagicHash"),(PolymorphicComponents,"-XPolymorphicComponents"),(ExistentialQuantification,"-XExistentialQuantification"),(KindSignatures,"-XKindSignatures"),(PatternSignatures,"-XPatternSignatures"),(EmptyDataDecls,"-XEmptyDataDecls"),(ParallelListComp,"-XParallelListComp"),(ForeignFunctionInterface,"-XForeignFunctionInterface"),(UnliftedFFITypes,"-XUnliftedFFITypes"),(LiberalTypeSynonyms,"-XLiberalTypeSynonyms"),(Rank2Types,"-XRank2Types"),(RankNTypes,"-XRankNTypes"),(TypeOperators,"-XTypeOperators"),(RecursiveDo,"-XRecursiveDo"),(Arrows,"-XArrows"),(UnknownExtension "PArr","-XPArr"),(TemplateHaskell,"-XTemplateHaskell"),(Generics,"-XGenerics"),(NoImplicitPrelude,"-XNoImplicitPrelude"),(RecordWildCards,"-XRecordWildCards"),(RecordPuns,"-XRecordPuns"),(DisambiguateRecordFields,"-XDisambiguateRecordFields"),(OverloadedStrings,"-XOverloadedStrings"),(GADTs,"-XGADTs"),(TypeFamilies,"-XTypeFamilies"),(BangPatterns,"-XBangPatterns"),(NoMonomorphismRestriction,"-XNoMonomorphismRestriction"),(NoMonoPatBinds,"-XNoMonoPatBinds"),(RelaxedPolyRec,"-XRelaxedPolyRec"),(ExtendedDefaultRules,"-XExtendedDefaultRules"),(ImplicitParams,"-XImplicitParams"),(ScopedTypeVariables,"-XScopedTypeVariables"),(UnboxedTuples,"-XUnboxedTuples"),(StandaloneDeriving,"-XStandaloneDeriving"),(DeriveDataTypeable,"-XDeriveDataTypeable"),(TypeSynonymInstances,"-XTypeSynonymInstances"),(FlexibleContexts,"-XFlexibleContexts"),(FlexibleInstances,"-XFlexibleInstances"),(ConstrainedClassMethods,"-XConstrainedClassMethods"),(MultiParamTypeClasses,"-XMultiParamTypeClasses"),(FunctionalDependencies,"-XFunctionalDependencies"),(GeneralizedNewtypeDeriving,"-XGeneralizedNewtypeDeriving"),(OverlappingInstances,"-XOverlappingInstances"),(UndecidableInstances,"-XUndecidableInstances"),(IncoherentInstances,"-XIncoherentInstances")]}, buildDir = "dist/build", scratchDir = "dist/scratch", packageDeps = [PackageIdentifier {pkgName = PackageName "base", pkgVersion = Version {versionBranch = [3,0,1,0], versionTags = []}},PackageIdentifier {pkgName = PackageName "containers", pkgVersion = Version {versionBranch = [0,1,0,1], versionTags = []}}], installedPkgs = PackageIndex (fromList [(PackageName "array",[InstalledPackageInfo {package = PackageIdentifier {pkgName = PackageName "array", pkgVersion = Version {versionBranch = [0,1,0,0], versionTags = []}}, license = BSD3, copyright = "", maintainer = "libraries@haskell.org", author = "", stability = "", homepage = "", pkgUrl = "", description = "This package defines the classes @IArray@ of immutable arrays and\n@MArray@ of arrays mutable within appropriate monads, as well as\nsome instances of these classes.", category = "", exposed = True, exposedModules = [ModuleName ["Data","Array"],ModuleName ["Data","Array","Base"],ModuleName ["Data","Array","Diff"],ModuleName ["Data","Array","IArray"],ModuleName ["Data","Array","IO"],ModuleName ["Data","Array","MArray"],ModuleName ["Data","Array","ST"],ModuleName ["Data","Array","Storable"],ModuleName ["Data","Array","Unboxed"]], hiddenModules = [ModuleName ["Data","Array","IO","Internals"]], importDirs = ["/usr/local/lib/ghc-6.8.2/lib/array-0.1.0.0"], libraryDirs = ["/usr/local/lib/ghc-6.8.2/lib/array-0.1.0.0"], hsLibraries = ["HSarray-0.1.0.0"], extraLibraries = [], extraGHCiLibraries = [], includeDirs = [], includes = [], depends = [PackageIdentifier {pkgName = PackageName "base", pkgVersion = Version {versionBranch = [3,0,1,0], versionTags = []}}], hugsOptions = [], ccOptions = [], ldOptions = [], frameworkDirs = [], frameworks = [], haddockInterfaces = ["/usr/local/share/doc/ghc/libraries/array/array.haddock"], haddockHTMLs = ["/usr/local/share/doc/ghc/libraries/array"]}]),(PackageName "base",[InstalledPackageInfo {package = PackageIdentifier {pkgName = PackageName "base", pkgVersion = Version {versionBranch = [3,0,1,0], versionTags = []}}, license = BSD3, copyright = "", maintainer = "libraries@haskell.org", author = "", stability = "", homepage = "", pkgUrl = "", description = "This package contains the Prelude and its support libraries,\nand a large collection of useful libraries ranging from data\nstructures to parsing combinators and debugging utilities.", category = "", exposed = True, exposedModules = [ModuleName ["Data","Generics"],ModuleName ["Data","Generics","Aliases"],ModuleName ["Data","Generics","Basics"],ModuleName ["Data","Generics","Instances"],ModuleName ["Data","Generics","Schemes"],ModuleName ["Data","Generics","Text"],ModuleName ["Data","Generics","Twins"],ModuleName ["Foreign","Concurrent"],ModuleName ["GHC","Arr"],ModuleName ["GHC","Base"],ModuleName ["GHC","Conc"],ModuleName ["GHC","ConsoleHandler"],ModuleName ["GHC","Dotnet"],ModuleName ["GHC","Enum"],ModuleName ["GHC","Environment"],ModuleName ["GHC","Err"],ModuleName ["GHC","Exception"],ModuleName ["GHC","Exts"],ModuleName ["GHC","Float"],ModuleName ["GHC","ForeignPtr"],ModuleName ["GHC","Handle"],ModuleName ["GHC","IO"],ModuleName ["GHC","IOBase"],ModuleName ["GHC","Int"],ModuleName ["GHC","List"],ModuleName ["GHC","Num"],ModuleName ["GHC","PArr"],ModuleName ["GHC","Pack"],ModuleName ["GHC","Prim"],ModuleName ["GHC","PrimopWrappers"],ModuleName ["GHC","Ptr"],ModuleName ["GHC","Read"],ModuleName ["GHC","Real"],ModuleName ["GHC","ST"],ModuleName ["GHC","STRef"],ModuleName ["GHC","Show"],ModuleName ["GHC","Stable"],ModuleName ["GHC","Storable"],ModuleName ["GHC","TopHandler"],ModuleName ["GHC","Unicode"],ModuleName ["GHC","Weak"],ModuleName ["GHC","Word"],ModuleName ["System","Timeout"],ModuleName ["Control","Applicative"],ModuleName ["Control","Arrow"],ModuleName ["Control","Concurrent"],ModuleName ["Control","Concurrent","Chan"],ModuleName ["Control","Concurrent","MVar"],ModuleName ["Control","Concurrent","QSem"],ModuleName ["Control","Concurrent","QSemN"],ModuleName ["Control","Concurrent","SampleVar"],ModuleName ["Control","Exception"],ModuleName ["Control","Monad"],ModuleName ["Control","Monad","Fix"],ModuleName ["Control","Monad","Instances"],ModuleName ["Control","Monad","ST"],ModuleName ["Control","Monad","ST","Lazy"],ModuleName ["Control","Monad","ST","Strict"],ModuleName ["Data","Bits"],ModuleName ["Data","Bool"],ModuleName ["Data","Char"],ModuleName ["Data","Complex"],ModuleName ["Data","Dynamic"],ModuleName ["Data","Either"],ModuleName ["Data","Eq"],ModuleName ["Data","Fixed"],ModuleName ["Data","Foldable"],ModuleName ["Data","Function"],ModuleName ["Data","HashTable"],ModuleName ["Data","IORef"],ModuleName ["Data","Int"],ModuleName ["Data","Ix"],ModuleName ["Data","List"],ModuleName ["Data","Maybe"],ModuleName ["Data","Monoid"],ModuleName ["Data","Ord"],ModuleName ["Data","Ratio"],ModuleName ["Data","STRef"],ModuleName ["Data","STRef","Lazy"],ModuleName ["Data","STRef","Strict"],ModuleName ["Data","String"],ModuleName ["Data","Traversable"],ModuleName ["Data","Tuple"],ModuleName ["Data","Typeable"],ModuleName ["Data","Unique"],ModuleName ["Data","Version"],ModuleName ["Data","Word"],ModuleName ["Debug","Trace"],ModuleName ["Foreign"],ModuleName ["Foreign","C"],ModuleName ["Foreign","C","Error"],ModuleName ["Foreign","C","String"],ModuleName ["Foreign","C","Types"],ModuleName ["Foreign","ForeignPtr"],ModuleName ["Foreign","Marshal"],ModuleName ["Foreign","Marshal","Alloc"],ModuleName ["Foreign","Marshal","Array"],ModuleName ["Foreign","Marshal","Error"],ModuleName ["Foreign","Marshal","Pool"],ModuleName ["Foreign","Marshal","Utils"],ModuleName ["Foreign","Ptr"],ModuleName ["Foreign","StablePtr"],ModuleName ["Foreign","Storable"],ModuleName ["Numeric"],ModuleName ["Prelude"],ModuleName ["System","Console","GetOpt"],ModuleName ["System","CPUTime"],ModuleName ["System","Environment"],ModuleName ["System","Exit"],ModuleName ["System","IO"],ModuleName ["System","IO","Error"],ModuleName ["System","IO","Unsafe"],ModuleName ["System","Info"],ModuleName ["System","Mem"],ModuleName ["System","Mem","StableName"],ModuleName ["System","Mem","Weak"],ModuleName ["System","Posix","Internals"],ModuleName ["System","Posix","Types"],ModuleName ["Text","ParserCombinators","ReadP"],ModuleName ["Text","ParserCombinators","ReadPrec"],ModuleName ["Text","Printf"],ModuleName ["Text","Read"],ModuleName ["Text","Read","Lex"],ModuleName ["Text","Show"],ModuleName ["Text","Show","Functions"],ModuleName ["Unsafe","Coerce"]], hiddenModules = [], importDirs = ["/usr/local/lib/ghc-6.8.2/lib/base-3.0.1.0"], libraryDirs = ["/usr/local/lib/ghc-6.8.2/lib/base-3.0.1.0"], hsLibraries = ["HSbase-3.0.1.0"], extraLibraries = [], extraGHCiLibraries = [], includeDirs = ["/usr/local/lib/ghc-6.8.2/lib/base-3.0.1.0/include"], includes = ["HsBase.h"], depends = [PackageIdentifier {pkgName = PackageName "rts", pkgVersion = Version {versionBranch = [1,0], versionTags = []}}], hugsOptions = [], ccOptions = [], ldOptions = [], frameworkDirs = [], frameworks = [], haddockInterfaces = ["/usr/local/share/doc/ghc/libraries/base/base.haddock"], haddockHTMLs = ["/usr/local/share/doc/ghc/libraries/base"]}]),(PackageName "containers",[InstalledPackageInfo {package = PackageIdentifier {pkgName = PackageName "containers", pkgVersion = Version {versionBranch = [0,1,0,1], versionTags = []}}, license = BSD3, copyright = "", maintainer = "libraries@haskell.org", author = "", stability = "", homepage = "", pkgUrl = "", description = "This package contains efficient general-purpose implementations\nof various basic immutable container types.  The declared cost of\neach operation is either worst-case or amortized, but remains\nvalid even if structures are shared.", category = "", exposed = True, exposedModules = [ModuleName ["Data","Graph"],ModuleName ["Data","IntMap"],ModuleName ["Data","IntSet"],ModuleName ["Data","Map"],ModuleName ["Data","Sequence"],ModuleName ["Data","Set"],ModuleName ["Data","Tree"]], hiddenModules = [], importDirs = ["/usr/local/lib/ghc-6.8.2/lib/containers-0.1.0.1"], libraryDirs = ["/usr/local/lib/ghc-6.8.2/lib/containers-0.1.0.1"], hsLibraries = ["HScontainers-0.1.0.1"], extraLibraries = [], extraGHCiLibraries = [], includeDirs = [], includes = [], depends = [PackageIdentifier {pkgName = PackageName "base", pkgVersion = Version {versionBranch = [3,0,1,0], versionTags = []}},PackageIdentifier {pkgName = PackageName "array", pkgVersion = Version {versionBranch = [0,1,0,0], versionTags = []}}], hugsOptions = [], ccOptions = [], ldOptions = [], frameworkDirs = [], frameworks = [], haddockInterfaces = ["/usr/local/share/doc/ghc/libraries/containers/containers.haddock"], haddockHTMLs = ["/usr/local/share/doc/ghc/libraries/containers"]}]),(PackageName "rts",[InstalledPackageInfo {package = PackageIdentifier {pkgName = PackageName "rts", pkgVersion = Version {versionBranch = [1,0], versionTags = []}}, license = BSD3, copyright = "", maintainer = "glasgow-haskell-users@haskell.org", author = "", stability = "", homepage = "", pkgUrl = "", description = "", category = "", exposed = True, exposedModules = [], hiddenModules = [], importDirs = [], libraryDirs = ["/usr/local/lib/ghc-6.8.2"], hsLibraries = ["HSrts"], extraLibraries = ["m","gmp","dl","rt"], extraGHCiLibraries = [], includeDirs = ["/usr/local/lib/ghc-6.8.2/include"], includes = ["Stg.h"], depends = [], hugsOptions = [], ccOptions = [], ldOptions = ["-u","base_GHCziBase_Izh_static_info","-u","base_GHCziBase_Czh_static_info","-u","base_GHCziFloat_Fzh_static_info","-u","base_GHCziFloat_Dzh_static_info","-u","base_GHCziPtr_Ptr_static_info","-u","base_GHCziWord_Wzh_static_info","-u","base_GHCziInt_I8zh_static_info","-u","base_GHCziInt_I16zh_static_info","-u","base_GHCziInt_I32zh_static_info","-u","base_GHCziInt_I64zh_static_info","-u","base_GHCziWord_W8zh_static_info","-u","base_GHCziWord_W16zh_static_info","-u","base_GHCziWord_W32zh_static_info","-u","base_GHCziWord_W64zh_static_info","-u","base_GHCziStable_StablePtr_static_info","-u","base_GHCziBase_Izh_con_info","-u","base_GHCziBase_Czh_con_info","-u","base_GHCziFloat_Fzh_con_info","-u","base_GHCziFloat_Dzh_con_info","-u","base_GHCziPtr_Ptr_con_info","-u","base_GHCziPtr_FunPtr_con_info","-u","base_GHCziStable_StablePtr_con_info","-u","base_GHCziBase_False_closure","-u","base_GHCziBase_True_closure","-u","base_GHCziPack_unpackCString_closure","-u","base_GHCziIOBase_stackOverflow_closure","-u","base_GHCziIOBase_heapOverflow_closure","-u","base_GHCziIOBase_NonTermination_closure","-u","base_GHCziIOBase_BlockedOnDeadMVar_closure","-u","base_GHCziIOBase_BlockedIndefinitely_closure","-u","base_GHCziIOBase_Deadlock_closure","-u","base_GHCziIOBase_NestedAtomically_closure","-u","base_GHCziWeak_runFinalizzerBatch_closure","-u","base_GHCziConc_ensureIOManagerIsRunning_closure"], frameworkDirs = [], frameworks = [], haddockInterfaces = [], haddockHTMLs = []}])]), pkgDescrFile = Just "./RefSerialize.cabal", localPkgDescr = PackageDescription {package = PackageIdentifier {pkgName = PackageName "RefSerialize", pkgVersion = Version {versionBranch = [0,2], versionTags = []}}, license = BSD3, licenseFile = "LICENSE", copyright = "", maintainer = "agocorona@gmail.com", author = "Alberto G\243mez Corona", stability = "", testedWith = [(GHC,ThisVersion (Version {versionBranch = [6,8,2], versionTags = []}))], homepage = "", pkgUrl = "", bugReports = "", sourceRepos = [], synopsis = "Write to and read from Strings maintaining internal memory references", description = "Read, Show and Data.Binary do not check for pointers to the same address\nas a result, the data is duplicated when serialized. This is a waste of space in the filesystem\nand  also a waste of serialization time. but the worst consequence is that, when the serialized data is read,\nit allocates multiple copies for the same object referenced multiple times. Because multiple referenced\ndata is very typical in a pure language such is Haskell, this means that the resulting data loose the beatiful\neconomy of space and processing time that referential transparency permits.\nThis package allows the serialization and deserialization of large data structures without duplication of data, with\nthe result of optimized performance and memory usage. It is also useful for debugging purposes.\nThere are automatic derived instances for instances of Read/Show, lists and strings. the deserializer\ncontains a subset of Parsec.Token for deserialization.\nEvery instance of Show/Read is also a instance of Data.RefSerialize\nthe serialized string has the form \"expr( var1, ...varn) where  var1=value1,..valn=valueN \" so that the\nstring can ve EVALuated.\nSee demo.hs and tutorial. I presumably will add a entry in haskell-web.blogspot.com\nTo develop: -derived instances for Data.Binary\n-serialization to/from ByteStings", category = "Middleware", customFieldsPD = [], buildDepends = [Dependency (PackageName "base") AnyVersion,Dependency (PackageName "containers") AnyVersion], descCabalVersion = UnionVersionRanges (ThisVersion (Version {versionBranch = [1,2], versionTags = []})) (LaterVersion (Version {versionBranch = [1,2], versionTags = []})), buildType = Just Simple, library = Just (Library {exposedModules = [ModuleName ["Data","RefSerialize"]], libExposed = True, libBuildInfo = BuildInfo {buildable = True, buildTools = [], cppOptions = [], ccOptions = [], ldOptions = [], pkgconfigDepends = [], frameworks = [], cSources = [], hsSourceDirs = ["."], otherModules = [], extensions = [], extraLibs = [], extraLibDirs = [], includeDirs = [], includes = [], installIncludes = [], options = [(GHC,[])], ghcProfOptions = [], ghcSharedOptions = [], customFieldsBI = []}}), executables = [], dataFiles = [], dataDir = "", extraSrcFiles = [], extraTmpFiles = []}, withPrograms = [("alex",ConfiguredProgram {programId = "alex", programVersion = Just (Version {versionBranch = [2,1,0], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/alex"}}),("ar",ConfiguredProgram {programId = "ar", programVersion = Nothing, programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/ar"}}),("c2hs",ConfiguredProgram {programId = "c2hs", programVersion = Just (Version {versionBranch = [0,15,1], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/local/bin/c2hs"}}),("gcc",ConfiguredProgram {programId = "gcc", programVersion = Just (Version {versionBranch = [4,1,3], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/gcc"}}),("ghc",ConfiguredProgram {programId = "ghc", programVersion = Just (Version {versionBranch = [6,8,2], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/local/bin/ghc"}}),("ghc-pkg",ConfiguredProgram {programId = "ghc-pkg", programVersion = Just (Version {versionBranch = [6,8,2], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/local/bin/ghc-pkg"}}),("haddock",ConfiguredProgram {programId = "haddock", programVersion = Just (Version {versionBranch = [0,8], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/haddock"}}),("happy",ConfiguredProgram {programId = "happy", programVersion = Just (Version {versionBranch = [1,17], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/local/bin/happy"}}),("hsc2hs",ConfiguredProgram {programId = "hsc2hs", programVersion = Just (Version {versionBranch = [0,66], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/local/bin/hsc2hs"}}),("ld",ConfiguredProgram {programId = "ld", programVersion = Nothing, programArgs = ["-x"], programLocation = FoundOnSystem {locationPath = "/usr/bin/ld"}}),("pkg-config",ConfiguredProgram {programId = "pkg-config", programVersion = Just (Version {versionBranch = [0,22], versionTags = []}), programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/pkg-config"}}),("ranlib",ConfiguredProgram {programId = "ranlib", programVersion = Nothing, programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/ranlib"}}),("strip",ConfiguredProgram {programId = "strip", programVersion = Nothing, programArgs = [], programLocation = FoundOnSystem {locationPath = "/usr/bin/strip"}}),("tar",ConfiguredProgram {programId = "tar", programVersion = Nothing, programArgs = [], programLocation = FoundOnSystem {locationPath = "/bin/tar"}})], withPackageDB = GlobalPackageDB, withVanillaLib = True, withProfLib = False, withSharedLib = False, withProfExe = False, withOptimization = NormalOptimisation, withGHCiLib = True, splitObjs = False, stripExes = True, progPrefix = "", progSuffix = ""}
+ tutorial.txt view
@@ -0,0 +1,95 @@+GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help+Loading package base ... linking ... done.+Prelude>:l Data.RefSerialize+ Ok, modules loaded: Data.RefSerialize, Data.Parser, Data.Serialize.+Loading package array-0.1.0.0 ... linking ... done.+Loading package containers-0.1.0.1 ... linking ... done.++runW applies showp, the serialization parser of the instance Int for the RefSerialize class++Data.RefSerialize>let x= 5 :: Int+Data.RefSerialize>runW $ showp x+Data.RefSerialize>"5"++every instance of Read and Show is an instance of RefSerialize. for how to construct showp and readp parsers, see the demo.hs++rshowp is derived from showp, it labels the serialized data with a variable name++Data.RefSerialize>runW $ rshowp x+Data.RefSerialize> " v8 where {v8= 5; }"++Data.RefSerialize>runW $ rshowp [2::Int,3::Int]+Data.RefSerialize> " v6 where {v6= [ v9,  v10]; v9= 2; v10= 3; }"++while showp does a normal show serialization++Data.RefSerialize>runW $ showp [x,x]+Data.RefSerialize> "[5, 5]"++rshowp variables are serialized memory references: no piece of data that point to the same addrees is serialized but one time++Data.RefSerialize>runW $ rshowp [x,x]+Data.RefSerialize> " v9 where {v6= 5; v9= [ v6, v6]; }"++"this happens recursively"++let xs= [x,x] in str = runW $ rshowp [xs,xs]+str+" v8 where {v8= [ v10, v10]; v9= 5; v10= [ v9, v9]; }"++the rshowp serialized data is read with rreadp. the showp serialized data is read by readp++Data.RefSerialize>let xss= runR rreadp str :: [[Int]]+Data.RefSerialize>print xss+[[5,5],[5,5]]++echo "this is the deserialized data"++the deserialized data keep the references!! pointers are restored! That is the whole point!++Data.RefSerialize>varName xss !! 0 == varName xss !! 1+True+++rShow= runW rshowp+rRead= runR rreadp++Data.RefSerialize>rShow x+" v11 where {v11= 5; }"+++In the definition of a referencing parser non referencing parsers can be used and viceversa. Use a referencing parser+when the piece of data is being referenced many times inside the serialized data.++by default the referencing parser is constructed by:++   rshowp= insertVar showp+   rreadp= readVar readp+but this can be redefined. See for example the instance of [] in RefSerialize.hs++This is an example of a showp parser for a simple data structure.++data S= S Int Int deriving ( Show, Eq)       ++instance  Serialize S  where+    showp (S x y)= do+                    xs <- rshowp x  -- rshowp parsers can be inside showp parser+                    ys <- rshowp y+                    return $ "S "++xs++" "++ys+       +       +there is a mix between referencing and no referencing parser here:     +  +Data.RefSerialize>putStrLn $ runW $ showp $ S x x+S  v23 v23 where {v23= 5; }     +    readp =  do+                    symbol "S"     -- I included a (almost) complete Parsec for deserialization+                    x <- rreadp    +                    y <- rreadp+                    return $ S x y++++++