Bytes.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Bytes.swift
  2. // This file is part of MiKee.
  3. //
  4. // Copyright © 2019 Maxime Epain. All rights reserved.
  5. //
  6. // MiKee is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // MiKee is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with MiKee. If not, see <https://www.gnu.org/licenses/>.
  18. import Foundation
  19. public func lenght<T>(_ bytes: Bytes) -> T where T: BinaryInteger {
  20. return T(bytes.rawValue.count)
  21. }
  22. public struct Bytes: RawRepresentable {
  23. public var rawValue: [UInt8]
  24. public var lenght: Int { rawValue.count }
  25. public var data: Data { Data(rawValue) }
  26. public var hexa: String {
  27. rawValue.map { .init(format: "%02x", $0) }.joined()
  28. }
  29. public init() {
  30. rawValue = []
  31. }
  32. public init(rawValue: [UInt8]) {
  33. self.rawValue = [UInt8](rawValue)
  34. }
  35. public init(_ buffer: UnsafeRawBufferPointer) {
  36. rawValue = Array(buffer)
  37. }
  38. public init(slice: ArraySlice<UInt8>) {
  39. rawValue = [UInt8](slice)
  40. }
  41. public init(lenght: Int) {
  42. self.init(rawValue: [UInt8](repeating: 0, count: lenght))
  43. }
  44. public init(repeating: UInt8, count: Int) {
  45. self.init(rawValue: [UInt8](repeating: repeating, count: count))
  46. }
  47. public init(random lenght: Int) throws {
  48. rawValue = (0 ..< lenght).map { _ in
  49. UInt8.random(in: UInt8.min ... UInt8.max)
  50. }
  51. }
  52. public init(data: Data) {
  53. rawValue = data.withUnsafeBytes { Array($0) }
  54. }
  55. public init(contentsOf url: URL) throws {
  56. let data = try Data(contentsOf: url)
  57. self.init(data: data)
  58. }
  59. public init?(string: String, using encoding: String.Encoding) {
  60. guard let data = string.data(using: encoding) else { return nil }
  61. self.init(data: data)
  62. }
  63. public init?(base64Encoded: String) {
  64. guard let data = Data(base64Encoded: base64Encoded) else { return nil }
  65. self.init(data: data)
  66. }
  67. public init?(hex: String) {
  68. let utf8 = [UInt8](hex.utf8)
  69. let offset = hex.hasPrefix("0x") ? 2 : 0
  70. var array = [UInt8]()
  71. let start = utf8.startIndex.advanced(by: offset)
  72. let end = utf8.endIndex
  73. let step = utf8.startIndex.advanced(by: 2)
  74. for index in stride(from: start, to: end, by: step) {
  75. let hex = "\(UnicodeScalar(utf8[index]))\(UnicodeScalar(utf8[index.advanced(by: 1)]))"
  76. guard let byte = UInt8(hex, radix: 16) else { return nil }
  77. array.append(byte)
  78. }
  79. rawValue = array
  80. }
  81. public subscript(index: Int) -> UInt8 {
  82. get { rawValue[index] }
  83. set { rawValue[index] = newValue }
  84. }
  85. public subscript(range: CountableRange<Int>) -> Bytes {
  86. Bytes(slice: rawValue[range])
  87. }
  88. public mutating func append(_ byte: UInt8) {
  89. rawValue.append(byte)
  90. }
  91. public mutating func append(_ bytes: [UInt8]) {
  92. rawValue.append(contentsOf: bytes)
  93. }
  94. public mutating func append(_ bytes: Bytes) {
  95. rawValue.append(contentsOf: bytes.rawValue)
  96. }
  97. @discardableResult
  98. public func withBytes<T>(_ body: ([UInt8]) -> T) -> T {
  99. body(rawValue)
  100. }
  101. @discardableResult
  102. public mutating func withMutableBytes<T>(_ body: (inout [UInt8]) -> T) -> T {
  103. body(&rawValue)
  104. }
  105. public func map<T>() -> [T] where T: BinaryInteger {
  106. map { T($0) }
  107. }
  108. public static func + (lhs: Bytes, rhs: Bytes) -> Bytes {
  109. Bytes(rawValue: lhs.rawValue + rhs.rawValue)
  110. }
  111. public static func += (lhs: inout Bytes, rhs: Bytes) {
  112. lhs = Bytes(rawValue: lhs.rawValue + rhs.rawValue)
  113. }
  114. public static func + (lhs: Bytes, rhs: UInt8) -> Bytes {
  115. Bytes(rawValue: lhs.rawValue + [rhs])
  116. }
  117. public static func += (lhs: inout Bytes, rhs: UInt8) {
  118. lhs.append(rhs)
  119. }
  120. }
  121. extension Bytes: Sequence {
  122. /// Returns an iterator over the elements of this sequence.
  123. public func makeIterator() -> IndexingIterator<[UInt8]> {
  124. rawValue.makeIterator()
  125. }
  126. /// A value less than or equal to the number of elements in the sequence,
  127. /// calculated nondestructively.
  128. ///
  129. /// The default implementation returns 0. If you provide your own
  130. /// implementation, make sure to compute the value nondestructively.
  131. ///
  132. /// - Complexity: O(1), except if the sequence also conforms to `Collection`.
  133. /// In this case, see the documentation of `Collection.underestimatedCount`.
  134. public var underestimatedCount: Int {
  135. rawValue.underestimatedCount
  136. }
  137. /// Call `body(p)`, where `p` is a pointer to the collection's
  138. /// contiguous storage. If no such storage exists, it is
  139. /// first created. If the collection does not support an internal
  140. /// representation in a form of contiguous storage, `body` is not
  141. /// called and `nil` is returned.
  142. ///
  143. /// A `Collection` that provides its own implementation of this method
  144. /// must also guarantee that an equivalent buffer of its `SubSequence`
  145. /// can be generated by advancing the pointer by the distance to the
  146. /// slice's `startIndex`.
  147. public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R? {
  148. try rawValue.withContiguousStorageIfAvailable(body)
  149. }
  150. }
  151. extension Bytes: ExpressibleByArrayLiteral {
  152. public init(arrayLiteral elements: UInt8...) {
  153. rawValue = elements
  154. }
  155. }
  156. extension Bytes: ContiguousBytes {
  157. /// Calls the given closure with the contents of underlying storage.
  158. ///
  159. /// - note: Calling `withUnsafeBytes` multiple times does not guarantee that
  160. /// the same buffer pointer will be passed in every time.
  161. /// - warning: The buffer argument to the body should not be stored or used
  162. /// outside of the lifetime of the call to the closure.
  163. public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
  164. try rawValue.withUnsafeBytes(body)
  165. }
  166. public mutating func withUnsafeMutableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
  167. try rawValue.withUnsafeMutableBytes(body)
  168. }
  169. }
  170. extension Bytes: DataProtocol {
  171. public var regions: CollectionOfOne<[UInt8]> { rawValue.regions }
  172. public var startIndex: Int { rawValue.startIndex }
  173. public var endIndex: Int { rawValue.endIndex }
  174. }
  175. extension Bytes: Hashable {
  176. /// Hashes the essential components of this value by feeding them into the
  177. /// given hasher.
  178. ///
  179. /// Implement this method to conform to the `Hashable` protocol. The
  180. /// components used for hashing must be the same as the components compared
  181. /// in your type's `==` operator implementation. Call `hasher.combine(_:)`
  182. /// with each of these components.
  183. ///
  184. /// - Important: Never call `finalize()` on `hasher`. Doing so may become a
  185. /// compile-time error in the future.
  186. ///
  187. /// - Parameter hasher: The hasher to use when combining the components
  188. /// of this instance.
  189. public func hash(into hasher: inout Hasher) {
  190. hasher.combine(rawValue)
  191. }
  192. }