SwiftProtobufContiguousBytes.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Sources/SwiftProtobuf/SwiftProtobufContiguousBytes.swift
  2. //
  3. // Copyright (c) 2022 Apple Inc. and the project authors
  4. // Licensed under Apache License v2.0 with Runtime Library Exception
  5. //
  6. // See LICENSE.txt for license information:
  7. // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
  8. //
  9. // -----------------------------------------------------------------------------
  10. import Foundation
  11. /// Conformance to this protocol gives users a way to provide their own "bag of bytes" types
  12. /// to be used for serialization and deserialization of protobufs.
  13. /// It provides a general interface for bytes since the Swift Standard Library currently does not
  14. /// provide such a protocol.
  15. ///
  16. /// By conforming your own types to this protocol, you will be able to pass instances of said types
  17. /// directly to `SwiftProtobuf.Message`'s deserialisation methods
  18. /// (i.e. `init(contiguousBytes:)` for binary format and `init(jsonUTF8Bytes:)` for JSON).
  19. public protocol SwiftProtobufContiguousBytes {
  20. /// An initializer for a bag of bytes type.
  21. ///
  22. /// - Parameters:
  23. /// - repeating: the byte value to be repeated.
  24. /// - count: the number of times to repeat the byte value.
  25. init(repeating: UInt8, count: Int)
  26. /// An initializer for a bag of bytes type, given a sequence of bytes.
  27. ///
  28. /// - Parameters:
  29. /// - sequence: a sequence of UInt8 from which the bag of bytes should be constructed.
  30. init<S: Sequence>(_ sequence: S) where S.Element == UInt8
  31. /// The number of bytes in the bag of bytes.
  32. var count: Int { get }
  33. /// Calls the given closure with the contents of underlying storage.
  34. ///
  35. /// - note: Calling `withUnsafeBytes` multiple times does not guarantee that
  36. /// the same buffer pointer will be passed in every time.
  37. /// - warning: The buffer argument to the body should not be stored or used
  38. /// outside of the lifetime of the call to the closure.
  39. func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
  40. /// Calls the given closure with the contents of underlying storage.
  41. ///
  42. /// - note: Calling `withUnsafeBytes` multiple times does not guarantee that
  43. /// the same buffer pointer will be passed in every time.
  44. /// - warning: The buffer argument to the body should not be stored or used
  45. /// outside of the lifetime of the call to the closure.
  46. mutating func withUnsafeMutableBytes<R>(_ body: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R
  47. }
  48. extension Array: SwiftProtobufContiguousBytes where Array.Element == UInt8 {}
  49. extension Data: SwiftProtobufContiguousBytes {}