summaryrefslogtreecommitdiff
path: root/Codec/Encryption/OpenPGP/ASCIIArmor/Utils.hs
blob: e36b8db8d430e127d8e6fe2d4f1afa5c7997051e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
-- ASCIIArmor/Utils.hs: OpenPGP (RFC4880) ASCII armor implementation
-- Copyright © 2012  Clint Adams
-- This software is released under the terms of the Expat license.
-- (See the LICENSE file).

module Codec.Encryption.OpenPGP.ASCIIArmor.Utils (
   crlfUnlines
 , crlfUnlinesLazy
) where

import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC8
import Data.List (intersperse)
import Data.Char (isSpace)

removeTrailingSpaces :: ByteString -> ByteString
removeTrailingSpaces bs = fst $ BC8.spanEnd isSpace bs

toLast :: (a -> a) -> [a] -> [a]
toLast _ []     = []
toLast f [x]    = [f x]
toLast f (x:xs) = x : toLast f xs

removeTrailingSpacesLazy :: BL.ByteString -> BL.ByteString
removeTrailingSpacesLazy bs = BL.fromChunks $ toLast removeTrailingSpaces $ BL.toChunks bs

crlfUnlines :: [ByteString] -> ByteString
crlfUnlines [] = B.empty
crlfUnlines ss = B.concat $ intersperse (BC8.pack "\r\n") $ map removeTrailingSpaces ss

crlfUnlinesLazy :: [BL.ByteString] -> BL.ByteString
crlfUnlinesLazy [] = BL.empty
crlfUnlinesLazy ss = BL.concat $ intersperse (BLC8.pack "\r\n") $ map removeTrailingSpacesLazy ss