-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBitStreamCodable.swift
36 lines (29 loc) · 992 Bytes
/
BitStreamCodable.swift
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
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Protocols for defining types that can encode to bit streams.
*/
import Foundation
protocol BitStreamEncodable {
func encode(to bitStream: inout WritableBitStream) throws
}
protocol BitStreamDecodable {
init(from bitStream: inout ReadableBitStream) throws
}
/// - Tag: BitStreamCodable
typealias BitStreamCodable = BitStreamEncodable & BitStreamDecodable
extension BitStreamEncodable where Self: Encodable {
func encode(to bitStream: inout WritableBitStream) throws {
let encoder = PropertyListEncoder()
encoder.outputFormat = .binary
let data = try encoder.encode(self)
bitStream.append(data)
}
}
extension BitStreamDecodable where Self: Decodable {
init(from bitStream: inout ReadableBitStream) throws {
let data = try bitStream.readData()
let decoder = PropertyListDecoder()
self = try decoder.decode(Self.self, from: data)
}
}