MaybeInplace.jl solves a common problem in Julia: code written for mutable arrays often fails when used with immutable arrays (like StaticArrays). This package provides macros (@bb, @bangbang, or @❗) that automatically rewrite operations to work with both mutable and immutable arrays, choosing in-place operations when possible and out-of-place operations when necessary.
MaybeInplace is a
Julia Language
package. To install MaybeInplace,
please open
Julia's interactive session (known as REPL) and press ] key in the REPL to use the package mode, then type the following command
pkg> add MaybeInplaceusing MaybeInplace, StaticArrays
# Without @bb: This function only works with mutable arrays
function add_arrays!(result, a, b)
result .= a .+ b
return result
end
# Works with regular arrays
add_arrays!([0.0, 0.0], [1.0, 2.0], [3.0, 4.0]) # ✓ Works
# Fails with StaticArrays (immutable)
# add_arrays!(@SVector[0.0, 0.0], @SVector[1.0, 2.0], @SVector[3.0, 4.0]) # ✗ Error!
# With @bb: This function works with both mutable and immutable arrays
function add_arrays_generic!(result, a, b)
@bb result .= a .+ b
return result
end
# Works with regular arrays (uses in-place operation)
add_arrays_generic!([0.0, 0.0], [1.0, 2.0], [3.0, 4.0]) # ✓ Returns [4.0, 6.0]
# Also works with StaticArrays (uses out-of-place operation)
add_arrays_generic!(@SVector[0.0, 0.0], @SVector[1.0, 2.0], @SVector[3.0, 4.0]) # ✓ Returns @SVector[4.0, 6.0]The @bb macro inspects the array at runtime and chooses the appropriate operation. For example:
@bb @. x = y + zbecomes:
if setindex_trait(x) === CanSetindex()
@. x = y + z # In-place for mutable arrays
else
x = @. y + z # Out-of-place for immutable arrays
endThe macro supports the following operations:
copyto!(y, x)- Copy operationsx .= <expr>- Broadcasting assignment@. <expr>- Broadcast macrox .+= <expr>,x .-= <expr>,x .*= <expr>,x ./= <expr>- Compound assignment operatorsx = copy(y)- Copy with assignmentx = similar(y)- Similar array creationx = zero(y)- Zero initializationaxpy!(a, x, y)- BLAS-style operationsx = y × z- Custom matrix multiplication operator (typed with\times<tab>)
For a complete list and detailed examples, see the docstring: ?@bb