-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONWriter.swift
More file actions
101 lines (83 loc) · 2.46 KB
/
JSONWriter.swift
File metadata and controls
101 lines (83 loc) · 2.46 KB
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
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
import Foundation
public class JSONWriter : Writer {
var tagMapStack: [[Int:(String, Bool)]] = []
var tagMap: [Int:(String, Bool)]! = nil
var objectStack: [NSMutableDictionary] = []
var object: NSMutableDictionary! = nil
var tag: Int! = nil
var isRepeatedStack: [Bool] = []
public class func writer() -> Writer? {
return JSONWriter()
}
public func toBuffer() -> NSData {
return try! NSJSONSerialization.dataWithJSONObject(object, options: [])
}
public func writeTag(tag: Int) {
self.tag = tag
}
public func writeByte(v: UInt8) {
self.writeValue(Int(v))
}
public func writeVarInt(v: Int) {
if 0 == tag & 0x02 {
self.writeValue(v)
}
}
public func writeVarUInt(v: UInt) {
self.writeValue(v)
}
public func writeVarUInt64(v: UInt64) {
self.writeValue(Int(v))
}
public func writeBool(v: Bool) {
self.writeValue(v)
}
public func writeData(v: NSData) {
NSException(name:"Unsupported Operation", reason:"", userInfo: nil).raise()
}
public func writeFloat32(v: Float32) {
self.writeValue(v)
}
public func writeFloat64(v: Float64) {
self.writeValue(v)
}
public func writeString(v: String) {
self.writeValue(v)
}
private func writeValue(v: AnyObject) {
self.writeValue(v, object: object)
}
private func writeValue(v: AnyObject, object: NSMutableDictionary) {
if let info = tagMap[tag] {
if info.1 {
if let array = object[info.0] as? NSMutableArray {
array.addObject(v)
} else {
object[info.0] = NSMutableArray(objects: v)
}
} else {
object[info.0] = v
}
} else {
// error
}
}
public func pushTagMap(map: [Int:(String, Bool)]) {
let parentObject = object
object = [:]
if tag != nil {
self.writeValue(object, object: parentObject)
}
if nil != tagMap {
tagMapStack.append(tagMap)
objectStack.append(parentObject)
}
tagMap = map
}
public func popTagMap() {
if tagMapStack.count > 0 {
tagMap = tagMapStack.removeLast()
object = objectStack.removeLast()
}
}
}