diff --git a/mojo/stdlib/src/memory/pointer.mojo b/mojo/stdlib/src/memory/pointer.mojo index db5c6af19c..4618617d99 100644 --- a/mojo/stdlib/src/memory/pointer.mojo +++ b/mojo/stdlib/src/memory/pointer.mojo @@ -341,6 +341,15 @@ struct Pointer[ """ self._value = _mlir_value + @always_inline("nodebug") + fn __init__(out self, *, ref [origin, address_space._value.value]to: type): + """Constructs a Pointer from a reference to a value. + + Args: + to: The value to construct a pointer to. + """ + self = Self(_mlir_value=__get_mvalue_as_litref(to)) + @staticmethod @always_inline("nodebug") fn address_of(ref [origin, address_space]value: type) -> Self: diff --git a/mojo/stdlib/src/memory/unsafe_pointer.mojo b/mojo/stdlib/src/memory/unsafe_pointer.mojo index 4ed238c03f..c20b990f3f 100644 --- a/mojo/stdlib/src/memory/unsafe_pointer.mojo +++ b/mojo/stdlib/src/memory/unsafe_pointer.mojo @@ -128,6 +128,15 @@ struct UnsafePointer[ """ self.address = value + @always_inline("nodebug") + fn __init__(out self, *, ref [origin, address_space._value.value]to: type): + """Constructs a Pointer from a reference to a value. + + Args: + to: The value to construct a pointer to. + """ + self = Self(__mlir_op.`lit.ref.to_pointer`(__get_mvalue_as_litref(to))) + @always_inline @implicit fn __init__( diff --git a/mojo/stdlib/test/memory/test_reference.mojo b/mojo/stdlib/test/memory/test_pointer.mojo similarity index 88% rename from mojo/stdlib/test/memory/test_reference.mojo rename to mojo/stdlib/test/memory/test_pointer.mojo index f9aabb0304..13b9ce9037 100644 --- a/mojo/stdlib/test/memory/test_reference.mojo +++ b/mojo/stdlib/test/memory/test_pointer.mojo @@ -11,7 +11,7 @@ # limitations under the License. # ===----------------------------------------------------------------------=== # # RUN: %mojo %s -from testing import assert_equal, assert_true +from testing import assert_equal, assert_true, assert_not_equal def test_copy_reference_explicitly(): @@ -41,7 +41,13 @@ def test_str(): assert_true(String(a_ref).startswith("0x")) +def test_pointer_to(): + var local = 1 + assert_not_equal(0, Pointer(to=local)[]) + + def main(): test_copy_reference_explicitly() test_equality() test_str() + test_pointer_to() diff --git a/mojo/stdlib/test/memory/test_unsafepointer.mojo b/mojo/stdlib/test/memory/test_unsafepointer.mojo index 4877b9a5b3..f86429d03b 100644 --- a/mojo/stdlib/test/memory/test_unsafepointer.mojo +++ b/mojo/stdlib/test/memory/test_unsafepointer.mojo @@ -101,6 +101,11 @@ def test_address_of(): _ = local +def test_pointer_to(): + var local = 1 + assert_not_equal(0, UnsafePointer(to=local)[]) + + def test_explicit_copy_of_pointer_address(): var local = 1 var ptr = UnsafePointer[Int].address_of(local) @@ -358,6 +363,7 @@ def test_volatile_load_and_store_simd(): def main(): test_address_of() + test_pointer_to() test_refitem() test_refitem_offset()