Skip to content

Commit 3dcad8c

Browse files
committed
[test] add tests for load and store from slices
1 parent cb2c58a commit 3dcad8c

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

validation-test/stdlib/UnsafeBufferPointerSlices.swift

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,4 +563,73 @@ UnsafeMutableRawBufferPointerSliceTests.test(
563563
})
564564
}
565565

566+
UnsafeMutableRawBufferPointerSliceTests.test(
567+
"slice.of.UnsafeMutableRawBufferPointer.load"
568+
) {
569+
let count = 4
570+
let sizeInBytes = count * MemoryLayout<Int>.stride
571+
let b = UnsafeMutableRawBufferPointer.allocate(
572+
byteCount: sizeInBytes, alignment: MemoryLayout<Int>.alignment
573+
)
574+
defer {
575+
b.deallocate()
576+
}
577+
b.withMemoryRebound(to: Int.self) {
578+
var (i, c) = $0.update(from: 1...count)
579+
expectEqual(c, count)
580+
expectNil(i.next())
581+
}
582+
expectEqual(
583+
1, b[...].load(as: Int.self)
584+
)
585+
expectEqual(
586+
2, b[...].load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self)
587+
)
588+
expectEqual(
589+
3, b[MemoryLayout<Int>.stride...].load(
590+
fromByteOffset: MemoryLayout<Int>.stride, as: Int.self
591+
)
592+
)
593+
}
594+
595+
UnsafeMutableRawBufferPointerSliceTests.test(
596+
"slice.of.UnsafeMutableRawBufferPointer.loadUnaligned"
597+
) {
598+
let count = 4
599+
let sizeInBytes = count * MemoryLayout<Int>.stride
600+
let b = UnsafeMutableRawBufferPointer.allocate(
601+
byteCount: sizeInBytes, alignment: MemoryLayout<Int>.alignment
602+
)
603+
defer {
604+
b.deallocate()
605+
}
606+
b.copyBytes(from: 0..<UInt8(sizeInBytes))
607+
let i = b[...].loadUnaligned(fromByteOffset: 3, as: Int.self)
608+
expectEqual(3, withUnsafeBytes(of: i, \.first))
609+
let i16 = b[7...].loadUnaligned(as: Int16.self)
610+
expectEqual(7, withUnsafeBytes(of: i16, \.first))
611+
let i32 = b[17...].loadUnaligned(fromByteOffset: 6, as: Int32.self)
612+
expectEqual(23, withUnsafeBytes(of: i32, \.first))
613+
}
614+
615+
UnsafeMutableRawBufferPointerSliceTests.test(
616+
"slice.of.UnsafeMutableRawBufferPointer.storeBytes"
617+
) {
618+
let count = 4
619+
let sizeInBytes = count * MemoryLayout<Int>.stride
620+
let b = UnsafeMutableRawBufferPointer.allocate(
621+
byteCount: sizeInBytes, alignment: MemoryLayout<Int>.alignment
622+
)
623+
defer {
624+
b.deallocate()
625+
}
626+
b.copyBytes(from: repeatElement(0, count: sizeInBytes))
627+
expectEqual(b[0], 0)
628+
b[...].storeBytes(of: .max, as: UInt8.self)
629+
expectEqual(b[0], .max)
630+
expectTrue(b[3..<3+MemoryLayout<UInt>.size].allSatisfy({ $0 == 0 }))
631+
b[3...].storeBytes(of: .max, toByteOffset: 4, as: UInt.self)
632+
expectTrue(b[7..<7+MemoryLayout<UInt>.size].allSatisfy({ $0 == .max }))
633+
}
634+
566635
runAllTests()

0 commit comments

Comments
 (0)