GRPCNIOTransportBytes.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. public struct GRPCNIOTransportBytes: GRPCContiguousBytes, Hashable, Sendable {
  20. @usableFromInline
  21. internal var buffer: ByteBuffer
  22. @inlinable
  23. internal init(_ buffer: ByteBuffer) {
  24. self.buffer = buffer
  25. }
  26. @inlinable
  27. internal init() {
  28. self.buffer = ByteBuffer()
  29. }
  30. @inlinable
  31. public init(repeating: UInt8, count: Int) {
  32. self.buffer = ByteBuffer(repeating: repeating, count: count)
  33. }
  34. @inlinable
  35. public init(_ sequence: some Sequence<UInt8>) {
  36. self.buffer = ByteBuffer(bytes: sequence)
  37. }
  38. @inlinable
  39. public var count: Int {
  40. self.buffer.readableBytes
  41. }
  42. @inlinable
  43. public func withUnsafeBytes<R>(
  44. _ body: (UnsafeRawBufferPointer) throws -> R
  45. ) rethrows -> R {
  46. try self.buffer.withUnsafeReadableBytes(body)
  47. }
  48. @inlinable
  49. public mutating func withUnsafeMutableBytes<R>(
  50. _ body: (UnsafeMutableRawBufferPointer) throws -> R
  51. ) rethrows -> R {
  52. // 'GRPCContiguousBytes' has no concept of readable/writable bytes; all bytes stored are
  53. // readable and writable. In 'ByteBuffer' terms, these are just the readable bytes.
  54. try self.buffer.withUnsafeMutableReadableBytes(body)
  55. }
  56. }