-
Notifications
You must be signed in to change notification settings - Fork 454
/
Copy pathData Conversion.swift
executable file
·107 lines (92 loc) · 2.91 KB
/
Data Conversion.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
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
102
103
104
105
106
//
// Data Conversion.swift
// BigInt
//
// Created by Károly Lőrentey on 2016-01-04.
// Copyright © 2016-2017 Károly Lőrentey.
//
import Foundation
extension BigUInt {
//MARK: NSData Conversion
public init(_ buffer: UnsafeRawBufferPointer) {
// This assumes Word is binary.
precondition(Word.bitWidth % 8 == 0)
self.init()
let length = buffer.count
guard length > 0 else { return }
let bytesPerDigit = Word.bitWidth / 8
var index = length / bytesPerDigit
var c = bytesPerDigit - length % bytesPerDigit
if c == bytesPerDigit {
c = 0
index -= 1
}
var word: Word = 0
for byte in buffer {
word <<= 8
word += Word(byte)
c += 1
if c == bytesPerDigit {
self[index] = word
index -= 1
c = 0
word = 0
}
}
assert(c == 0 && word == 0 && index == -1)
}
/// Initializes an integer from the bits stored inside a piece of `Data`.
/// The data is assumed to be in network (big-endian) byte order.
public init(_ data: Data) {
// This assumes Word is binary.
precondition(Word.bitWidth % 8 == 0)
self.init()
let length = data.count
guard length > 0 else { return }
let bytesPerDigit = Word.bitWidth / 8
var index = length / bytesPerDigit
var c = bytesPerDigit - length % bytesPerDigit
if c == bytesPerDigit {
c = 0
index -= 1
}
var word: Word = 0
data.enumerateBytes { p, byteIndex, stop in
for byte in p {
word <<= 8
word += Word(byte)
c += 1
if c == bytesPerDigit {
self[index] = word
index -= 1
c = 0
word = 0
}
}
}
assert(c == 0 && word == 0 && index == -1)
}
/// Return a `Data` value that contains the base-256 representation of this integer, in network (big-endian) byte order.
public func serialize() -> Data {
// This assumes Digit is binary.
precondition(Word.bitWidth % 8 == 0)
let byteCount = (self.bitWidth + 7) / 8
guard byteCount > 0 else { return Data() }
var data = Data(count: byteCount)
data.withUnsafeMutableBytes { (p: UnsafeMutablePointer<UInt8>) -> Void in
var i = byteCount - 1
for var word in self.words {
for _ in 0 ..< Word.bitWidth / 8 {
p[i] = UInt8(word & 0xFF)
word >>= 8
if i == 0 {
assert(word == 0)
break
}
i -= 1
}
}
}
return data
}
}