Skip to content

Commit

Permalink
More robust append using singletonof
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Nov 4, 2019
1 parent 6b729fc commit e98160c
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/BangBang.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ using LinearAlgebra
using Requires
using ZygoteRules: @adjoint

# Used in NoBang:
function ismutable end
function push!! end

include("NoBang/NoBang.jl")
using .NoBang: ImmutableContainer, singletonof

Expand Down
2 changes: 2 additions & 0 deletions src/NoBang/NoBang.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ using Base: ImmutableDict
using Requires
using ConstructionBase: constructorof, setproperties

using ..BangBang: push!!, ismutable

if VERSION < v"1.1-"
using Future: copy!
end
Expand Down
17 changes: 16 additions & 1 deletion src/NoBang/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,22 @@ _append(xs, ys) = append!(copy(xs), ys)
_append(xs, ys::Tuple) = push(xs, ys...)
_append(xs, ys::Pairs{Symbol, <:Any, <:Any, <:NamedTuple}) = push(xs, ys...)

append(xs::AbstractVector, ys::AbstractVector) = vcat(xs, ys)
append(xs::AbstractVector, ys::AbstractVector) =
if constructorof(typeof(xs)) === constructorof(typeof(ys))
vcat(xs, ys)
elseif !ismutable(xs) && ismutable(ys)
vcat(xs, ys)
elseif length(ys) == 0
xs
#=
elseif length(ys) == 1
push(xs, ys[1])
=#
else
# Not so robust:
# append!!(push(xs, ys[1]), @view ys[2:end])
foldl(push!!, (@view ys[2:end]), init=push(xs, ys[1]))
end

append(xs::ImmutableContainer, ys) = push(xs, ys...)

Expand Down
13 changes: 13 additions & 0 deletions test/test_typedtables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,17 @@ using TypedTables
@test tints == Table(a = [1, 3], b = [2, 4])
end

@testset "append!!" begin
tints = Table(a = [1], b = [2])
@test append!!(tints, [(a = 3.0, b = 4.0)])::Table == Table(
a = [1.0, 3.0],
b = [2.0, 4.0],
)
@test tints == Table(a = [1], b = [2])

tints = Table(a = [1], b = [2])
@test_broken append!!(tints, [(a = 3, b = 4)]) === tints
@test_broken tints == Table(a = [1, 3], b = [2, 4])
end

end # module

0 comments on commit e98160c

Please sign in to comment.