Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define over' to make the laziness avoidance more readable. #130

Merged
merged 1 commit into from
Aug 31, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions proto-lens/src/Data/ProtoLens/Encoding.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.ProtoLens.Encoding(
encodeMessage,
Expand All @@ -36,7 +37,7 @@ import qualified Data.ByteString as B
import qualified Data.Map.Strict as Map
import Data.ByteString.Lazy.Builder as Builder
import qualified Data.ByteString.Lazy as L
import Lens.Family2 (set, over, (^.), (&))
import Lens.Family2 (Lens', set, over, (^.), (&))

-- TODO: We could be more incremental when parsing/encoding length-based fields,
-- rather than forcing the whole thing. E.g., for encoding we're doing extra
Expand Down Expand Up @@ -120,10 +121,10 @@ parseAndAddField
RepeatedField _ f
-> (do
!x <- getSimpleVal
return $! over f (\(!xs) -> x:xs) msg)
return $! over' f (x :) msg)
<|> (do
xs <- getPackedVals
return $! over f (\(!ys) -> xs++ys) msg)
return $! over' f (xs ++) msg)
<|> fail ("Field " ++ name
++ "expects a repeated field wire type but found "
++ show wt)
Expand All @@ -135,6 +136,15 @@ parseAndAddField
(Map.insert key value)
msg

-- | Strict version of 'over' that forces the old value.
-- Helps prevent gross space leaks when modifying a list field.
--
-- In particular, a naive `@over f (x :) y@ keeps the old value of @y@ around
-- in a thunk, because @(:)@ isn't strict in its second argument. (Similarly
-- for @(++)@.)
over' :: Lens' a b -> (b -> b) -> a -> a
over' f g = over f (\(!x) -> g x)

-- | Run the parser zero or more times, until the "end" parser succeeds.
-- Returns a list of the parsed elements, in reverse order.
manyReversedTill :: Parser a -> Parser b -> Parser [a]
Expand Down