You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.9 KiB

2 years ago
  1. //////////////////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Data+Extensions.swift
  4. // Starscream
  5. //
  6. // Created by Dalton Cherry on 3/27/19.
  7. // Copyright © 2019 Vluxe. All rights reserved.
  8. //
  9. // Fix for deprecation warnings
  10. //
  11. // Licensed under the Apache License, Version 2.0 (the "License");
  12. // you may not use this file except in compliance with the License.
  13. // You may obtain a copy of the License at
  14. //
  15. // http://www.apache.org/licenses/LICENSE-2.0
  16. //
  17. // Unless required by applicable law or agreed to in writing, software
  18. // distributed under the License is distributed on an "AS IS" BASIS,
  19. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. // See the License for the specific language governing permissions and
  21. // limitations under the License.
  22. //
  23. //////////////////////////////////////////////////////////////////////////////////////////////////
  24. import Foundation
  25. internal extension Data {
  26. struct ByteError: Swift.Error {}
  27. #if swift(>=5.0)
  28. func withUnsafeBytes<ResultType, ContentType>(_ completion: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
  29. return try withUnsafeBytes {
  30. if let baseAddress = $0.baseAddress, $0.count > 0 {
  31. return try completion(baseAddress.assumingMemoryBound(to: ContentType.self))
  32. } else {
  33. throw ByteError()
  34. }
  35. }
  36. }
  37. #endif
  38. #if swift(>=5.0)
  39. mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ completion: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
  40. return try withUnsafeMutableBytes {
  41. if let baseAddress = $0.baseAddress, $0.count > 0 {
  42. return try completion(baseAddress.assumingMemoryBound(to: ContentType.self))
  43. } else {
  44. throw ByteError()
  45. }
  46. }
  47. }
  48. #endif
  49. }