-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample.swift
More file actions
90 lines (79 loc) · 2.49 KB
/
Example.swift
File metadata and controls
90 lines (79 loc) · 2.49 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
import Foundation
import SwiftMsgPack
struct Example: MessagePackable {
var name: String = "John Doe"
var age: Int = 42
var data: Data = Data([0x01, 0x02, 0x03])
var array: [Int] = [1, 2, 3]
var map: [String: Int] = ["a": 1, "b": 2, "c": 3]
var timestamp: Date = Date()
var optional: Int? = nil
func packValue() -> MessagePackValue {
return .structure([
.string(name, encoding: .utf8),
.value(age),
.valueWithOption(data, option: .bin_8),
.value(array),
.value(map),
.value(timestamp),
.value(optional),
])
}
// func packValue() -> MessagePackValue {
// return .structureAsExt(
// id: 24,
// [
// .string(name, encoding: .utf8),
// .value(age),
// .valueWithOption(data, option: .bin_8),
// .value(array),
// .value(map),
// .date(timestamp, format: .timestamp_64),
// ],
// constraint: .ext_32 // Optional
// )
// }
}
@main
public struct ExampleApp {
static func main() {
// Synchronous
syncPackUnpack()
// Asynchonous
if #available(macOS 10.15.0, iOS 15.0, *) {
Task {
await asyncPackUnpack()
}
}
sleep(1)
}
static func syncPackUnpack() {
print()
let example = Example()
do {
let packed: Data = try example.pack().get()
print("Packed:\n\(packed.withUnsafeBytes(Array.init))")
let unpacked: [Any?] = try MessagePackData(data: packed).unpack().get()
print("Unpacked:\n\(unpacked)")
// Int and Int64 are packed as Int64 but unpacked as Int64 only, same goes for UInt and UInt64:
let _ = unpacked[1] as! Int64
} catch {
print("Unpacking error: \(error)")
}
print()
}
@available(macOS 10.15.0, iOS 15.0, *)
static func asyncPackUnpack() async {
print("Async:")
let example = Example()
do {
let packed = try await example.pack().get()
print("Packed async:\n\(packed.withUnsafeBytes(Array.init))")
let unpacked: [Any?] = try await MessagePackData(data: packed).unpack().get()
print("Unpacked async:\n\(unpacked)")
} catch {
print("Unpacking async error: \(error)")
}
print()
}
}