@@ -8548,3 +8548,44 @@ func TestValuePointerAndUnsafePointer(t *testing.T) {
8548
8548
})
8549
8549
}
8550
8550
}
8551
+
8552
+ // Test cases copied from ../../test/unsafebuiltins.go
8553
+ func TestSliceAt (t * testing.T ) {
8554
+ const maxUintptr = 1 << (8 * unsafe .Sizeof (uintptr (0 )))
8555
+ var p [10 ]byte
8556
+
8557
+ typ := TypeOf (p [0 ])
8558
+
8559
+ s := SliceAt (typ , unsafe .Pointer (& p [0 ]), len (p ))
8560
+ if s .Pointer () != uintptr (unsafe .Pointer (& p [0 ])) {
8561
+ t .Fatalf ("unexpected underlying array: %d, want: %d" , s .Pointer (), uintptr (unsafe .Pointer (& p [0 ])))
8562
+ }
8563
+ if s .Len () != len (p ) || s .Cap () != len (p ) {
8564
+ t .Fatalf ("unexpected len or cap, len: %d, cap: %d, want: %d" , s .Len (), s .Cap (), len (p ))
8565
+ }
8566
+
8567
+ typ = TypeOf (0 )
8568
+ if ! SliceAt (typ , unsafe .Pointer ((* int )(nil )), 0 ).IsNil () {
8569
+ t .Fatal ("nil pointer with zero length must return nil" )
8570
+ }
8571
+
8572
+ // nil pointer with positive length panics
8573
+ shouldPanic ("" , func () { _ = SliceAt (typ , unsafe .Pointer ((* int )(nil )), 1 ) })
8574
+
8575
+ // negative length
8576
+ var neg int = - 1
8577
+ shouldPanic ("" , func () { _ = SliceAt (TypeOf (byte (0 )), unsafe .Pointer (& p [0 ]), neg ) })
8578
+
8579
+ // size overflows address space
8580
+ n := uint64 (0 )
8581
+ shouldPanic ("" , func () { _ = SliceAt (TypeOf (n ), unsafe .Pointer (& n ), maxUintptr / 8 ) })
8582
+ shouldPanic ("" , func () { _ = SliceAt (TypeOf (n ), unsafe .Pointer (& n ), maxUintptr / 8 + 1 ) })
8583
+
8584
+ // sliced memory overflows address space
8585
+ last := (* byte )(unsafe .Pointer (^ uintptr (0 )))
8586
+ // This panics here, but won't panic in ../../test/unsafebuiltins.go,
8587
+ // because unsafe.Slice(last, 1) does not escape.
8588
+ //
8589
+ // _ = SliceAt(typ, unsafe.Pointer(last), 1)
8590
+ shouldPanic ("" , func () { _ = SliceAt (typ , unsafe .Pointer (last ), 2 ) })
8591
+ }
0 commit comments