forked from danielpaulus/quicktime_video_hack
/
dict_serializer.go
71 lines (65 loc) · 2.01 KB
/
dict_serializer.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package coremedia
import (
"encoding/binary"
"log"
"github.com/DineshKuppan/quicktime_video_hack/screencapture/common"
)
// SerializeStringKeyDict serializes a StringKeyDict into a []byte
func SerializeStringKeyDict(stringKeyDict StringKeyDict) []byte {
buffer := make([]byte, 1024*1024)
var slice = buffer[8:]
var index = 0
for _, entry := range stringKeyDict.Entries {
keyvaluePair := slice[index+8:]
keyLength := serializeKey(entry.Key, keyvaluePair)
valueLength := serializeValue(entry.Value, keyvaluePair[keyLength:])
common.WriteLengthAndMagic(slice[index:], keyLength+valueLength+8, KeyValuePairMagic)
index += 8 + valueLength + keyLength
}
dictSizePlusHeaderAndLength := index + 4 + 4
common.WriteLengthAndMagic(buffer, dictSizePlusHeaderAndLength, DictionaryMagic)
return buffer[:dictSizePlusHeaderAndLength]
}
func serializeValue(value interface{}, bytes []byte) int {
switch value := value.(type) {
case bool:
common.WriteLengthAndMagic(bytes, 9, BooleanValueMagic)
var boolValue uint32
if value {
boolValue = 1
}
binary.LittleEndian.PutUint32(bytes[8:], boolValue)
return 9
case common.NSNumber:
numberBytes := value.ToBytes()
length := len(numberBytes) + 8
common.WriteLengthAndMagic(bytes, length, common.NumberValueMagic)
copy(bytes[8:], numberBytes)
return length
case string:
stringValue := value
length := len(stringValue) + 8
common.WriteLengthAndMagic(bytes, length, StringValueMagic)
copy(bytes[8:], stringValue)
return length
case []byte:
byteValue := value
length := len(byteValue) + 8
common.WriteLengthAndMagic(bytes, length, DataValueMagic)
copy(bytes[8:], byteValue)
return length
case StringKeyDict:
dictValue := SerializeStringKeyDict(value)
copy(bytes, dictValue)
return len(dictValue)
default:
log.Fatalf("Wrong type while serializing dict:%s", value)
}
return 0
}
func serializeKey(key string, bytes []byte) int {
keyLength := len(key) + 8
common.WriteLengthAndMagic(bytes, keyLength, StringKey)
copy(bytes[8:], key)
return keyLength
}