From 6a4971e7ec1a21579c309b04b42fd1070040113f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Helge=20He=C3=9F?= Date: Thu, 12 Dec 2024 17:21:48 +0100 Subject: [PATCH] If Foundation is available, mark `Buffer` as `ContiguousBytes` Useful in other contexts. --- Sources/MacroCore/Buffer/BufferData.swift | 25 +++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/Sources/MacroCore/Buffer/BufferData.swift b/Sources/MacroCore/Buffer/BufferData.swift index e4fb0eb..bc66d39 100644 --- a/Sources/MacroCore/Buffer/BufferData.swift +++ b/Sources/MacroCore/Buffer/BufferData.swift @@ -3,12 +3,13 @@ // Macro // // Created by Helge Heß. -// Copyright © 2020-2023 ZeeZide GmbH. All rights reserved. +// Copyright © 2020-2024 ZeeZide GmbH. All rights reserved. // #if canImport(Foundation) -import struct Foundation.Data +import struct Foundation.Data +import protocol Foundation.ContiguousBytes import NIOCore import NIOFoundationCompat @@ -17,16 +18,32 @@ public extension Buffer { /** * Initialize the Buffer with the contents of the given `Data`. Copies the * bytes. + * + * - Parameters: + * - data: The bytes to copy into the buffer. */ - @inlinable init(_ data: Data) { + @inlinable + init(_ data: Data) { self.init(capacity: data.count) byteBuffer.writeBytes(data) } - @inlinable var data : Data { + @inlinable + var data : Data { return byteBuffer.getData(at : byteBuffer.readerIndex, length : byteBuffer.readableBytes) ?? Data() } } +extension Buffer: ContiguousBytes { + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) + rethrows -> R + { + return try byteBuffer.readableBytesView.withUnsafeBytes(body) + } + +} + #endif // canImport(Foundation)