WireFormat.hs 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
-- Copyright (c) 2013, Kenton Varda <temporal@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.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.

24
module WireFormat(encodeMessage) where
25

26 27 28
import Data.List(sortBy, genericLength, genericReplicate)
import Data.Word
import Data.Bits(shiftL, shiftR, Bits, setBit)
29 30
import qualified Data.Set as Set
import Semantics
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
import Data.Binary.IEEE754(floatToWord, doubleToWord)
import qualified Codec.Binary.UTF8.String as UTF8

--
byte :: (Integral a, Bits a) => a -> Int -> Word8
byte i amount = fromIntegral (shiftR i (amount * 8))

bytes :: (Integral a, Bits a) => a -> Int -> [Word8]
bytes i count = map (byte i) [0..(count - 1)]

padToWord b = let
    trailing = mod (length b) 8
    in if trailing == 0
        then b
        else b ++ replicate (8 - trailing) 0

roundUpToMultiple factor n = let
    remainder = mod n factor
    in if remainder == 0
        then n
        else n + (factor - remainder)

encodeDataValue :: ValueDesc -> [Word8]
encodeDataValue VoidDesc = []
encodeDataValue (BoolDesc _) = error "Bools must be handled specially."
encodeDataValue (Int8Desc v) = bytes v 1
encodeDataValue (Int16Desc v) = bytes v 2
encodeDataValue (Int32Desc v) = bytes v 4
encodeDataValue (Int64Desc v) = bytes v 8
encodeDataValue (UInt8Desc v) = bytes v 1
encodeDataValue (UInt16Desc v) = bytes v 2
encodeDataValue (UInt32Desc v) = bytes v 4
encodeDataValue (UInt64Desc v) = bytes v 8
encodeDataValue (Float32Desc v) = bytes (floatToWord v) 4
encodeDataValue (Float64Desc v) = bytes (doubleToWord v) 8
encodeDataValue (TextDesc _) = error "Not fixed-width data."
encodeDataValue (DataDesc _) = error "Not fixed-width data."
encodeDataValue (EnumValueValueDesc v) = bytes (enumValueNumber v) 2
encodeDataValue (StructValueDesc _) = error "Not fixed-width data."
encodeDataValue (ListDesc _) = error "Not fixed-width data."

packBits :: Bits a => Int -> [Bool] -> a
packBits _ [] = 0
packBits offset (True:bits) = setBit (packBits (offset + 1) bits) offset
packBits offset (False:bits) = packBits (offset + 1) bits

encodeData :: Integer -> [(Integer, TypeDesc, ValueDesc)] -> [Word8]
encodeData size = loop 0 where
    loop bit [] | bit == size = []
    loop bit [] | bit > size = error "Data values overran size."
    loop bit [] = 0:loop (bit + 8) []
    loop bit rest@((valuePos, _, BoolDesc _):_) | valuePos == bit = let
        (bits, rest2) = popBits (bit + 8) rest
        in packBits 0 bits : loop (bit + 8) rest2
    loop bit ((valuePos, _, value):rest) | valuePos == bit =
        encodeDataValue value ++ loop (bit + sizeInBits (fieldValueSize value)) rest
    loop bit rest@((valuePos, _, _):_) | valuePos > bit = 0 : loop (bit + 8) rest
    loop _ _ = error "Data values were out-of-order."

    popBits limit ((valuePos, _, BoolDesc b):rest) | valuePos < limit = let
        (restBits, rest2) = popBits limit rest
        in (b:restBits, rest2)
    popBits _ rest = ([], rest)

encodeReferences :: Integer -> Integer -> [(Integer, TypeDesc, ValueDesc)] -> ([Word8], [Word8])
encodeReferences o size = loop 0 (o + size) where
    loop idx offset ((pos, t, v):rest) | idx == pos = let
        (ref, obj) = case (t, v) of
            (StructType desc, StructValueDesc assignments) -> let
                (dataBytes, refBytes, childBytes) = encodeStruct desc assignments 0
                in (encodeStructReference desc offset, concat [dataBytes, refBytes, childBytes])
            (ListType elementType, ListDesc items) ->
103
                (encodeListReference (elementSize elementType) (genericLength items) offset,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
                 encodeList elementType items)
            (BuiltinType BuiltinText, TextDesc text) -> let
                encoded = (UTF8.encode text ++ [0])
                in (encodeListReference Size8 (genericLength encoded) offset, padToWord encoded)
            (BuiltinType BuiltinData, DataDesc d) -> let
                in (encodeListReference Size8 (genericLength d) offset, padToWord d)
            _ -> error "Unknown reference type."
        len = genericLength obj
        wordLen = if mod len 8 == 0 then div len 8 else error "Child not word-aligned."
        (refs, objects) = loop (idx + 1) (offset + wordLen - 1) rest
        in (ref ++ refs, obj ++ objects)
    loop idx offset rest@((pos, _, _):_) = let
        padCount = pos - idx
        (refs, objects) = loop pos (offset - padCount) rest
        in (genericReplicate (padCount * 8) 0 ++ refs, objects)
    loop idx _ [] = (genericReplicate ((size - idx) * 8) 0, [])

121 122 123 124 125 126 127 128 129 130 131 132 133 134
encodeStructList :: Integer -> StructDesc -> [[(FieldDesc, ValueDesc)]] -> ([Word8], [Word8])
encodeStructList o desc elements = loop (o + eSize * genericLength elements) elements where
    eSize = packingSize $ structPacking desc
    loop _ [] = ([], [])
    loop offset (element:rest) = let
        offsetFromElementEnd = offset - eSize
        (dataBytes, refBytes, childBytes) = encodeStruct desc element offsetFromElementEnd
        childLen = genericLength childBytes
        childWordLen = if mod childLen 8 == 0
            then div childLen 8
            else error "Child not word-aligned."
        (restBytes, restChildren) = loop (offsetFromElementEnd + childWordLen) rest
        in (dataBytes ++ refBytes ++ restBytes, childBytes ++ restChildren)

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
encodeStructReference desc offset =
    bytes (offset * 4 + structTag) 4 ++
    [ fromIntegral (length (structFields desc) + length (structUnions desc))
    , fromIntegral $ packingDataSize $ structPacking desc
    , fromIntegral $ packingReferenceCount $ structPacking desc
    , 0 ]

encodeListReference elemSize@(SizeInlineComposite ds rc) elementCount offset =
    bytes (offset * 4 + listTag) 4 ++
    bytes (shiftL (fieldSizeEnum elemSize) 29 + elementCount * (ds + rc)) 4
encodeListReference elemSize elementCount offset =
    bytes (offset * 4 + listTag) 4 ++
    bytes (shiftL (fieldSizeEnum elemSize) 29 + elementCount) 4

fieldSizeEnum Size0 = 0
fieldSizeEnum Size1 = 1
fieldSizeEnum Size8 = 2
fieldSizeEnum Size16 = 3
fieldSizeEnum Size32 = 4
fieldSizeEnum Size64 = 5
fieldSizeEnum SizeReference = 6
fieldSizeEnum (SizeInlineComposite _ _) = 7

structTag = 0
listTag = 1
160 161 162 163 164 165 166

-- Is this field a non-retroactive member of a union?  If so, its default value is not written.
isNonRetroUnionMember (FieldDesc {fieldNumber = n, fieldUnion = Just u}) = n > unionNumber u
isNonRetroUnionMember _ = False

-- What is this union's default tag value?  If there is a retroactive field, it is that field's
-- number, otherwise it is the union's number (meaning no field set).
167 168
unionDefault desc = UInt8Desc $ fromIntegral $
    max (minimum $ map fieldNumber $ unionFields desc) (unionNumber desc)
169

170 171 172 173
-- childOffset = number of words between the last reference and the location where children will
-- be allocated.
encodeStruct desc assignments childOffset = (dataBytes, referenceBytes, children) where
    explicitlyAssignedNums = Set.fromList [fieldNumber f | (f, _) <- assignments]
174 175 176 177 178 179 180 181 182 183
    explicitlyAssignedUnions = Set.fromList
        [unionNumber u | (FieldDesc {fieldUnion = Just u}, _) <- assignments]

    -- Was this field explicitly assigned, or was another member of the same union explicitly
    -- assigned?  If so, its default value is not written.
    isExplicitlyAssigned (FieldDesc {fieldNumber = n, fieldUnion = u}) =
        Set.member n explicitlyAssignedNums ||
        maybe False (flip Set.member explicitlyAssignedUnions . unionNumber) u

    -- Values explicitly assigned.
184
    explicitValues = [(fieldOffset f, fieldType f, v) | (f, v) <- assignments]
185 186

    -- Values from defaults.
187
    defaultValues = [(o, fieldType field, v)
188
        | field@(FieldDesc { fieldOffset = o, fieldDefaultValue = Just v}) <- structFields desc
189
        -- Don't include default values for fields that were explicitly assigned.
190
        , not $ isExplicitlyAssigned field
191 192 193 194 195 196
        -- Don't encode defaults for union members since they'd overwrite each other, and anyway
        -- they wouldn't be valid unless the union tag specified them, which by default it doesn't,
        -- except of course in the case of retroactively-added fields.  So do include retro fields.
        , not $ isNonRetroUnionMember field
        -- Don't encode defaults for references.  Setting them to null has the same effect.
        , isDataFieldSize $ fieldValueSize v ]
197 198

    -- Values of union tags.
199
    unionValues = [(unionTagOffset u, BuiltinType BuiltinUInt8, UInt8Desc $ fromIntegral n)
200 201
                  | (FieldDesc {fieldUnion = Just u, fieldNumber = n}, _) <- assignments]

202 203 204
    -- Default values of union tags.
    unionDefaultValues = [(unionTagOffset u, BuiltinType BuiltinUInt8, unionDefault u)
                         | u <- structUnions desc
205 206 207
                         , not $ Set.member (unionNumber u) explicitlyAssignedUnions]

    allValues = explicitValues ++ defaultValues ++ unionValues ++ unionDefaultValues
208 209 210 211
    allData = [ (o * sizeInBits (fieldValueSize v), t, v)
              | (o, t, v) <- allValues, isDataFieldSize $ fieldValueSize v ]
    allReferences = [ (o, t, v) | (o, t, v) <- allValues
                    , not $ isDataFieldSize $ fieldValueSize v ]
212 213 214

    sortedData = sortBy compareValues allData
    sortedReferences = sortBy compareValues allReferences
215 216 217 218 219 220 221
    compareValues (o1, _, _) (o2, _, _) = compare o1 o2

    dataBytes = encodeData (packingDataSize (structPacking desc) * 64) sortedData
    (referenceBytes, children) = encodeReferences childOffset
        (packingReferenceCount $ structPacking desc) sortedReferences

encodeList elementType elements = case elementSize elementType of
222
    SizeInlineComposite _ _ -> case elementType of
223 224 225
        StructType desc -> let
            count = genericLength elements
            tag = encodeStructReference desc count
226 227
            (elemBytes, childBytes) = encodeStructList 0 desc [v | StructValueDesc v <- elements]
            in concat [tag, elemBytes, childBytes]
228 229 230 231
        _ -> error "Only structs can be inline composites."
    SizeReference -> refBytes ++ childBytes where
        (refBytes, childBytes) = encodeReferences 0 (genericLength elements)
                               $ zipWith (\i v -> (i, elementType, v)) [0..] elements
232
    size -> encodeData (roundUpToMultiple 64 (genericLength elements * sizeInBits size))
233
          $ zipWith (\i v -> (i * sizeInBits size, elementType, v)) [0..] elements
234

235 236 237 238 239 240 241
encodeMessage (StructType desc) (StructValueDesc assignments) = let
    (dataBytes, refBytes, childBytes) = encodeStruct desc assignments 0
    in concat [encodeStructReference desc (1::Integer), dataBytes, refBytes, childBytes]
encodeMessage (ListType elementType) (ListDesc elements) =
    encodeListReference (elementSize elementType) (genericLength elements) (1::Integer) ++
    encodeList elementType elements
encodeMessage _ _ = error "Not a message."