Skip to content

Commit cb1a0ae

Browse files
authored
Expose Core.memoryrefoffset as Base.memoryindex (#59600)
This exposes Core.memoryrefoffset as API through a generic function - currently the public, unexported `Base.memoryindex` This closes #59574.
1 parent 9534147 commit cb1a0ae

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

base/genericmemory.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,27 @@ IndexStyle(::Type{<:GenericMemory}) = IndexLinear()
6565

6666
parent(ref::GenericMemoryRef) = ref.mem
6767

68+
"""
69+
memoryindex(ref::GenericMemoryRef)::Int
70+
71+
Get the 1-based index of `ref` in its `GenericMemory`.
72+
73+
# Examples
74+
```jldoctest
75+
julia> mem = Memory{String}(undef, 10);
76+
77+
julia> ref = Base.memoryindex(memoryref(mem, 3))
78+
3
79+
80+
julia> Base.memoryindex(memoryref(Memory{Nothing}(undef, 10), 8))
81+
8
82+
```
83+
84+
!!! compat "Julia 1.13"
85+
This function requires at least Julia 1.13.
86+
"""
87+
memoryindex(ref::GenericMemoryRef) = memoryrefoffset(ref)
88+
6889
pointer(mem::GenericMemoryRef) = unsafe_convert(Ptr{Cvoid}, mem) # no bounds check, even for empty array
6990

7091
_unsetindex!(A::Memory, i::Int) = (@_propagate_inbounds_meta; _unsetindex!(memoryref(A, i)); A)

base/public.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public
3434
# arrays
3535
has_offset_axes,
3636
require_one_based_indexing,
37+
memoryindex,
3738

3839
# collections
3940
IteratorEltype,

doc/src/base/arrays.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Base.GenericMemory
3434
Base.Memory
3535
Base.Memory(::UndefInitializer, ::Int)
3636
Base.memoryref
37+
Base.memoryindex
3738
Base.Slices
3839
Base.RowSlices
3940
Base.ColumnSlices

test/arrayops.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3403,4 +3403,11 @@ end
34033403
mem = Memory{Float32}(undef, 3)
34043404
ref = memoryref(mem, 2)
34053405
@test parent(ref) === mem
3406+
@test Base.memoryindex(ref) === 2
3407+
3408+
# Test for zero-sized structs
3409+
mem = Memory{Nothing}(undef, 10)
3410+
ref = memoryref(mem, 8)
3411+
@test parent(ref) === mem
3412+
@test Base.memoryindex(ref) === 8
34063413
end

0 commit comments

Comments
 (0)