about summary refs log tree commit diff
path: root/tests/codegen
diff options
context:
space:
mode:
authorAndre Bogus <bogusandre@gmail.com>2022-12-18 15:40:46 +0100
committerAndre Bogus <bogusandre@gmail.com>2023-03-01 00:05:31 +0100
commit41da875faef58e618cafc7dfdc5f3985a58f1e98 (patch)
tree1200a1f2eb32151c90896d1d440aaaadda550b6c /tests/codegen
parentbd4a96a12d0bf6dc12edf20a45df3a33052c9d7d (diff)
downloadrust-41da875faef58e618cafc7dfdc5f3985a58f1e98.tar.gz
rust-41da875faef58e618cafc7dfdc5f3985a58f1e98.zip
Add `Option::as_slice`(`_mut`)
This adds the following functions:

* `Option<T>::as_slice(&self) -> &[T]`
* `Option<T>::as_slice_mut(&mut self) -> &[T]`

The `as_slice` and `as_slice_mut` functions benefit from an
optimization that makes them completely branch-free.

Note that the optimization's soundness hinges on the fact that either
the niche optimization makes the offset of the `Some(_)` contents zero
or the mempory layout of `Option<T>` is equal to that of
`Option<MaybeUninit<T>>`.
Diffstat (limited to 'tests/codegen')
-rw-r--r--tests/codegen/option-as-slice.rs28
1 files changed, 28 insertions, 0 deletions
diff --git a/tests/codegen/option-as-slice.rs b/tests/codegen/option-as-slice.rs
new file mode 100644
index 00000000000..d5077dbf6cc
--- /dev/null
+++ b/tests/codegen/option-as-slice.rs
@@ -0,0 +1,28 @@
+// compile-flags: -O
+// only-x86_64
+
+#![crate_type = "lib"]
+#![feature(option_as_slice)]
+
+extern crate core;
+
+use core::num::NonZeroU64;
+use core::option::Option;
+
+// CHECK-LABEL: @u64_opt_as_slice
+#[no_mangle]
+pub fn u64_opt_as_slice(o: &Option<u64>) -> &[u64] {
+    // CHECK: start:
+    // CHECK-NOT: select
+    // CHECK: ret
+    o.as_slice()
+}
+
+// CHECK-LABEL: @nonzero_u64_opt_as_slice
+#[no_mangle]
+pub fn nonzero_u64_opt_as_slice(o: &Option<NonZeroU64>) -> &[NonZeroU64] {
+    // CHECK: start:
+    // CHECK-NOT: select
+    // CHECK: ret
+    o.as_slice()
+}