summaryrefslogtreecommitdiffhomepage
path: root/Serialization.hs
blob: 4d6a671a48190efc4a5b3389cebb0cdbe7cb972e (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
37
38
39
40
41
42
43
44
45
46
47
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings #-}

{- Copyright 2016 Joey Hess <id@joeyh.name>
 -
 - Licensed under the GNU AGPL version 3 or higher.
 -}

module Serialization where

import Types
import Raaz.Core.Encode
import qualified Data.ByteString as B
import Data.Monoid
import Data.Word

-- | A KeyId is serialized in the form "keytype value".
-- For example "gpg C910D9222512E3C7"
instance Encodable KeyId where
	toByteString (KeyId (KeyType t) i) =
		t <> B.singleton sepChar <> i
	fromByteString b = case B.break (== sepChar) b of
		(t, n)
			| B.null n -> Nothing
			| otherwise -> Just $
				KeyId (KeyType t) (B.drop 1 n)

instance Encodable Name where
	toByteString (Name n) = n
	fromByteString = Just . Name

instance Encodable StorableObjectIdent where
	toByteString (StorableObjectIdent i) = i
	fromByteString = Just . StorableObjectIdent

instance Encodable StorableObject where
	 toByteString (StorableObject b) = b
	 fromByteString = Just . StorableObject

-- | A shard is serialized without its shard number. This prevents
-- an attacker from partitioning their shards by shard number.
instance Encodable Shard where
	toByteString (Shard _n o) = toByteString o
	fromByteString _ = Nothing

sepChar :: Word8
sepChar = 32