Skip to content

Commit a7a4c86

Browse files
committed
tests for ref setindex
1 parent 229dd6f commit a7a4c86

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/setindex.jl

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ Base.@propagate_inbounds function setindex(args...)
22
Base.setindex(args...)
33
end
44

5+
@inline setindex(::Base.RefValue, val) = Ref(val)
6+
57
Base.@propagate_inbounds function setindex(xs::AbstractArray, v, I...)
68
T = promote_type(eltype(xs), typeof(v))
79
ys = similar(xs, T)
@@ -21,8 +23,3 @@ Base.@propagate_inbounds function setindex(d0::AbstractDict, v, k)
2123
return d
2224
end
2325

24-
Base.@propagate_inbounds function setindex(ref::Base.RefValue{Tx}, val::Ty) where {Tx, Ty}
25-
T = promote_type(Tx, Ty)
26-
new_ref = Base.RefValue{T}(convert(T, val))
27-
return new_ref
28-
end

test/test_setindex.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ Check that _type_ and value of `x` and `y` are equal.
1515
@test !(1.0 ==1)
1616
end
1717

18+
function ref_alloc_test()
19+
ref = Ref((; a = 10, b = 0x0001, c = (; aa = 300)))
20+
ref2 = Accessors.setindex(ref, (; a = 10, b = ref[].b - 1, c = (; aa = 300)))
21+
ref3 = Accessors.setindex(ref, ref2[])
22+
23+
ref3[]
24+
end
25+
1826
@testset "setindex" begin
1927
arr = [1,2,3]
2028
@test_throws MethodError Base.setindex(arr, 10, 1)
@@ -32,6 +40,15 @@ end
3240
@test d == Dict(:a => 1, :b => 2)
3341
@test Accessors.setindex(d, 30, "c") ==Dict(:a=>1, :b=>2, "c"=>30)
3442
@test Accessors.setindex(d, 10.0, :a) ==Dict(:a=>10.0, :b=>2.0)
43+
44+
ref = Ref((; a = 10, b = 0x0001, c = (; aa = 300)))
45+
@test @set(ref[].a = 90)[] == Ref((; a = 90, b = 0x0001, c = (; aa = 300)))[]
46+
@test @set(ref[].b = Bool(ref[].b))[] == Ref((; a = 10, b = true, c = (; aa = 300)))[]
47+
@test @set(ref[].c.aa = 3)[] == Ref((; a = 10, b = 0x0001, c = (; aa = 3)))[]
48+
49+
local val
50+
@test @allocated(val = ref_alloc_test()) == 0
51+
@test val == (; a = 10, b = 0x0000, c = (; aa = 300))
3552
end
3653

3754
end

0 commit comments

Comments
 (0)