Skip to content

Commit 5757e6a

Browse files
authored
Merge pull request #22 from balenamiaa/master
setindex for ref
2 parents c698369 + b1abd26 commit 5757e6a

File tree

4 files changed

+27
-2
lines changed

4 files changed

+27
-2
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "Accessors"
22
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
33
authors = ["Takafumi Arakaki <[email protected]>", "Jan Weidner <[email protected]> and contributors"]
4-
version = "0.1.1"
4+
version = "0.1.2"
55

66
[deps]
77
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"

src/optics.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ function _modify(f, obj, optic::ComposedOptic, ::ModifyBased)
160160
end
161161
end
162162

163-
function _modify(f, obj, optic, ::SetBased)
163+
@inline function _modify(f, obj, optic, ::SetBased)
164164
set(obj, optic, f(optic(obj)))
165165
end
166166

src/setindex.jl

Lines changed: 3 additions & 0 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)
@@ -20,3 +22,4 @@ Base.@propagate_inbounds function setindex(d0::AbstractDict, v, k)
2022
d[k] = v
2123
return d
2224
end
25+

test/test_setindex.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ 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((UInt(10), 100))
20+
ref2 = @set ref[][1] *= -1
21+
22+
ref2[]
23+
end
24+
1825
@testset "setindex" begin
1926
arr = [1,2,3]
2027
@test_throws MethodError Base.setindex(arr, 10, 1)
@@ -32,6 +39,21 @@ end
3239
@test d == Dict(:a => 1, :b => 2)
3340
@test Accessors.setindex(d, 30, "c") ==Dict(:a=>1, :b=>2, "c"=>30)
3441
@test Accessors.setindex(d, 10.0, :a) ==Dict(:a=>10.0, :b=>2.0)
42+
43+
ref = Ref((; a = 1, b = 2, c = (; aa = 3)))
44+
@test @set(ref[].a = 90)[] == (; a = 90, b = 2, c = (; aa = 3))
45+
@test @set(ref[].b = "2")[] ==ₜ (; a = 1, b = "2", c = (; aa = 3))
46+
@test @set(ref[].c.aa += 2)[] == (; a = 1, b = 2, c = (; aa = 5))
47+
48+
ref = Ref(1::Int)
49+
@set ref[] = "no mutation"
50+
@test ref[] === 1
51+
@test typeof(ref) == Base.RefValue{Int}
52+
53+
if VERSION >= v"1.5.0"
54+
_ = ref_alloc_test()
55+
@test @allocated(ref_alloc_test()) == 0
56+
end
3557
end
3658

3759
end

0 commit comments

Comments
 (0)