When we pass some special words, NSString.getBytes does not crash even when we pass an invalid range.
It seems a bug.
The below code is an example.
func testNSStringGetBytes() {
let originalString: String = "あ"
let bufferSize = 256
var buffer = [UInt8](repeating: 0, count: bufferSize)
var usedLength = 0
// An invalid range is passed
let range = NSRange(location: 0, length: originalString.count + 1)
var remainingRange = NSRange()
(originalString as NSString)
.getBytes(
&buffer,
maxLength: bufferSize,
usedLength: &usedLength,
encoding: String.Encoding.utf8.rawValue,
options: [],
range: range,
remaining: &remainingRange
)
print("Used Length: \(usedLength)")
print("Buffer: \(buffer[0..<usedLength])")
if remainingRange.length > 0 {
print("Did not convert the whole string. Remaining range: \(remainingRange)")
} else {
print("Entire string was converted successfully.")
}
}