-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Extensions.swift
104 lines (77 loc) · 2.42 KB
/
Extensions.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
// MARK: - String
extension String {
public func padLeft(toLength newLength: Int) -> String {
return self.createPadding(newLength) + self
}
public func padRight(toLength newLength: Int) -> String {
return self + self.createPadding(newLength)
}
private func createPadding(_ newLength: Int) -> String {
// self.count is O(n)
let currentCount = self.count
if currentCount >= newLength {
return ""
}
let padCount = newLength - currentCount
return String(repeating: " ", count: padCount)
}
}
// MARK: - Numbers
extension UInt8 {
public var dec: String {
let s = String(self, radix: 10, uppercase: false)
let padding = String(repeating: " ", count: 3 - s.count)
return "\(padding)\(s)"
}
public var hex: String {
let s = String(self, radix: 16, uppercase: false)
let padding = String(repeating: "0", count: 2 - s.count)
return "0x\(padding)\(s)"
}
public var bin: String {
let s = String(self, radix: 2, uppercase: false)
let padding = String(repeating: "0", count: 8 - s.count)
return "0b\(padding)\(s)"
}
}
extension UInt16 {
public var dec: String {
let s = String(self, radix: 10, uppercase: false)
let padding = String(repeating: " ", count: 5 - s.count)
return "\(padding)\(s)"
}
public var hex: String {
let s = String(self, radix: 16, uppercase: false)
let padding = String(repeating: "0", count: 4 - s.count)
return "0x\(padding)\(s)"
}
public var bin: String {
let s = String(self, radix: 2, uppercase: false)
let padding = String(repeating: "0", count: 16 - s.count)
return "0b\(padding)\(s)"
}
}
// MARK: - Data
extension Data {
public subscript(index: UInt16) -> UInt8 {
get { return self[Int(index)] }
set { self[Int(index)] = newValue }
}
}
// MARK: - Range
extension Range {
/// First element included in range
public var start: Bound { return self.lowerBound }
/// Last element included in range
public var end: Bound { return self.upperBound }
}
extension ClosedRange {
/// First element included in range
public var start: Bound { return self.lowerBound }
/// Last element included in range
public var end: Bound { return self.upperBound }
}