forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefvalue.jl
60 lines (50 loc) · 1.73 KB
/
refvalue.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# This file is a part of Julia. License is MIT: https://julialang.org/license
### Methods for a Ref object that can store a single value of any type
mutable struct RefValue{T} <: Ref{T}
x::T
RefValue{T}() where {T} = new()
RefValue{T}(x) where {T} = new(x)
end
RefValue(x::T) where {T} = RefValue{T}(x)
"""
isassigned(ref::RefValue) -> Bool
Test whether the given [`Ref`](@ref) is associated with a value.
This is always true for a [`Ref`](@ref) of a bitstype object.
Return `false` if the reference is undefined.
# Examples
```jldoctest
julia> ref = Ref{Function}()
Base.RefValue{Function}(#undef)
julia> isassigned(ref)
false
julia> ref[] = (foobar(x) = x)
foobar (generic function with 1 method)
julia> isassigned(ref)
true
julia> isassigned(Ref{Int}())
true
```
"""
isassigned(x::RefValue) = isdefined(x, :x)
function unsafe_convert(P::Union{Type{Ptr{T}},Type{Ptr{Cvoid}}}, b::RefValue{T})::P where T
if allocatedinline(T)
p = pointer_from_objref(b)
elseif isconcretetype(T) && ismutabletype(T)
p = pointer_from_objref(b.x)
else
# If the slot is not leaf type, it could be either immutable or not.
# If it is actually an immutable, then we can't take it's pointer directly
# Instead, explicitly load the pointer from the `RefValue`,
# which also ensures this returns same pointer as the one rooted in the `RefValue` object.
p = atomic_pointerref(Ptr{Ptr{Cvoid}}(pointer_from_objref(b)), :monotonic)
if p == C_NULL
throw(UndefRefError())
end
end
return p
end
function unsafe_convert(::Type{Ptr{Any}}, b::RefValue{Any})::Ptr{Any}
return pointer_from_objref(b)
end
getindex(b::RefValue) = b.x
setindex!(b::RefValue, x) = (b.x = x; b)