Bytes.swift 7.6 KB

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