Skip to content

Commit

Permalink
Merge pull request JuliaObjects#22 from balenamiaa/master
Browse files Browse the repository at this point in the history
setindex for ref
  • Loading branch information
jw3126 authored Apr 7, 2021
2 parents 187aa28 + eb4268a commit a0a488c
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "Accessors"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
authors = ["Takafumi Arakaki <aka.tkf@gmail.com>", "Jan Weidner <jw3126@gmail.com> and contributors"]
version = "0.1.1"
version = "0.1.2"

[deps]
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"
Expand Down
2 changes: 1 addition & 1 deletion src/optics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ function _modify(f, obj, optic::ComposedOptic, ::ModifyBased)
end
end

function _modify(f, obj, optic, ::SetBased)
@inline function _modify(f, obj, optic, ::SetBased)
set(obj, optic, f(optic(obj)))
end

Expand Down
3 changes: 3 additions & 0 deletions src/setindex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ Base.@propagate_inbounds function setindex(args...)
Base.setindex(args...)
end

@inline setindex(::Base.RefValue, val) = Ref(val)

Base.@propagate_inbounds function setindex(xs::AbstractArray, v, I...)
T = promote_type(eltype(xs), typeof(v))
ys = similar(xs, T)
Expand All @@ -20,3 +22,4 @@ Base.@propagate_inbounds function setindex(d0::AbstractDict, v, k)
d[k] = v
return d
end

22 changes: 22 additions & 0 deletions test/test_setindex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ Check that _type_ and value of `x` and `y` are equal.
@test !(1.0 ==1)
end

function ref_alloc_test()
ref = Ref((UInt(10), 100))
ref2 = @set ref[][1] *= -1

ref2[]
end

@testset "setindex" begin
arr = [1,2,3]
@test_throws MethodError Base.setindex(arr, 10, 1)
Expand All @@ -32,6 +39,21 @@ end
@test d == Dict(:a => 1, :b => 2)
@test Accessors.setindex(d, 30, "c") ==Dict(:a=>1, :b=>2, "c"=>30)
@test Accessors.setindex(d, 10.0, :a) ==Dict(:a=>10.0, :b=>2.0)

ref = Ref((; a = 1, b = 2, c = (; aa = 3)))
@test @set(ref[].a = 90)[] == (; a = 90, b = 2, c = (; aa = 3))
@test @set(ref[].b = "2")[] ==ₜ (; a = 1, b = "2", c = (; aa = 3))
@test @set(ref[].c.aa += 2)[] == (; a = 1, b = 2, c = (; aa = 5))

ref = Ref(1::Int)
@set ref[] = "no mutation"
@test ref[] === 1
@test typeof(ref) == Base.RefValue{Int}

if VERSION >= v"1.5.0"
_ = ref_alloc_test()
@test @allocated(ref_alloc_test()) == 0
end
end

end

0 comments on commit a0a488c

Please sign in to comment.