|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +extension String { |
| 14 | + static func _tryFromUTF8(_ input: BufferView<UInt8>) -> String? { |
| 15 | + input.withUnsafePointer { pointer, capacity in |
| 16 | + _tryFromUTF8(.init(start: pointer, count: capacity)) |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +extension Data { |
| 22 | + func withBufferView<ResultType>( |
| 23 | + _ body: (BufferView<UInt8>) throws -> ResultType |
| 24 | + ) rethrows -> ResultType { |
| 25 | + try withUnsafeBytes { |
| 26 | + // Data never passes an empty buffer with a `nil` `baseAddress`. |
| 27 | + try body(BufferView(unsafeRawBufferPointer: $0)!) |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +extension BufferView { |
| 33 | + internal subscript(region: JSONMap.Region) -> BufferView { |
| 34 | + precondition( |
| 35 | + region.startOffset >= 0 && region.startOffset < count && region.count >= 0 |
| 36 | + && region.count <= count && region.startOffset &+ region.count <= count |
| 37 | + ) |
| 38 | + return self[unchecked: region] |
| 39 | + } |
| 40 | + |
| 41 | + internal subscript(unchecked region: JSONMap.Region) -> BufferView { |
| 42 | + let address = startIndex._rawValue.advanced(by: region.startOffset) |
| 43 | + return BufferView(baseAddress: address, count: region.count) |
| 44 | + } |
| 45 | +} |
0 commit comments