GRPCNIOTransportBytes.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2025, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. public import GRPCCore
  17. public import NIOCore
  18. /// The contiguous bytes type used by the gRPC's NIO transport.
  19. @available(gRPCSwiftNIOTransport 2.0, *)
  20. public struct GRPCNIOTransportBytes: GRPCContiguousBytes, Hashable, Sendable {
  21. @usableFromInline
  22. internal var buffer: ByteBuffer
  23. @inlinable
  24. internal init(_ buffer: ByteBuffer) {
  25. self.buffer = buffer
  26. }
  27. @inlinable
  28. internal init() {
  29. self.buffer = ByteBuffer()
  30. }
  31. @inlinable
  32. public init(repeating: UInt8, count: Int) {
  33. self.buffer = ByteBuffer(repeating: repeating, count: count)
  34. }
  35. @inlinable
  36. public init(_ sequence: some Sequence<UInt8>) {
  37. self.buffer = ByteBuffer(bytes: sequence)
  38. }
  39. @inlinable
  40. public var count: Int {
  41. self.buffer.readableBytes
  42. }
  43. @inlinable
  44. public func withUnsafeBytes<R>(
  45. _ body: (UnsafeRawBufferPointer) throws -> R
  46. ) rethrows -> R {
  47. try self.buffer.withUnsafeReadableBytes(body)
  48. }
  49. @inlinable
  50. public mutating func withUnsafeMutableBytes<R>(
  51. _ body: (UnsafeMutableRawBufferPointer) throws -> R
  52. ) rethrows -> R {
  53. // 'GRPCContiguousBytes' has no concept of readable/writable bytes; all bytes stored are
  54. // readable and writable. In 'ByteBuffer' terms, these are just the readable bytes.
  55. try self.buffer.withUnsafeMutableReadableBytes(body)
  56. }
  57. }