forked from mironal/TwitterAPIKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData.swift
More file actions
76 lines (65 loc) · 2.17 KB
/
Data.swift
File metadata and controls
76 lines (65 loc) · 2.17 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
import CommonCrypto
import Foundation
extension Data {
func hmac(key: Data) -> Data {
// Thanks: https://github.com/jernejstrasner/SwiftCrypto
let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
return withUnsafeBytes { bytes -> Data in
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: digestLen)
defer {
result.deallocate()
}
key.withUnsafeBytes { body in
CCHmac(
CCHmacAlgorithm(kCCHmacAlgSHA1),
body.baseAddress,
key.count, bytes.baseAddress,
count,
result
)
}
return Data(bytes: result, count: digestLen)
}
}
func split(separator: Data, omittingEmptySubsequences: Bool = true) -> [Data] {
var current = startIndex
var chunks = [Data]()
while let range = self[current...].range(of: separator) {
if !omittingEmptySubsequences {
chunks.append(self[current..<range.lowerBound])
} else if range.lowerBound > current {
chunks.append(self[current..<range.lowerBound])
}
current = range.upperBound
}
if current < self.endIndex {
chunks.append(self[current...])
}
return chunks
}
func serialize() -> Result<Any, TwitterAPIKitError> {
do {
let jsonObj = try JSONSerialization.jsonObject(with: self, options: [])
return .success(jsonObj)
} catch let error {
return .failure(
.responseSerializeFailed(
reason: .jsonSerializationFailed(error: error)
)
)
}
}
func decode<T: Decodable>(
_ type: T.Type,
decoder: JSONDecoder
) -> Result<T, TwitterAPIKitError> {
let result: Result<T, Error> = .init {
return try decoder.decode(type, from: self)
}
return result.mapError { error in
return .responseSerializeFailed(
reason: .jsonDecodeFailed(error: error)
)
}
}
}