Skip to content

Commit

Permalink
Add Base.alignment methods (#752)
Browse files Browse the repository at this point in the history
  • Loading branch information
sostock authored Dec 20, 2024
1 parent 1912abe commit eb46f21
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
4 changes: 2 additions & 2 deletions docs/src/conversion.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,13 @@ julia> [1.0u"m", 2.0u"m"]
julia> [1.0u"m", 2.0u"cm"]
2-element Vector{Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}}:
1.0 m
1.0 m
0.02 m
julia> [1.0u"m", 2.0]
2-element Vector{Quantity{Float64}}:
1.0 m
2.0
2.0
```

In the first case, an array with a concrete type is created. Good
Expand Down
16 changes: 16 additions & 0 deletions src/display.jl
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,19 @@ superscript(i::Integer) = map(repr(i)) do c
c == '0' ? '\u2070' :
error("unexpected character")
end

if isdefined(Base, :alignment_from_show)
printed_length(io, x) = Base.alignment_from_show(io, x)
else
printed_length(io, x) = length(sprint(show, x, context=io))
end

function Base.alignment(io::IO, x::Quantity)
if isunitless(unit(x))
return Base.alignment(io, x.val)
end
length = printed_length(io, x)
left, _ = Base.alignment(io, x.val)
left += BracketStyle(x.val) != NoBrackets()
return left, length - left
end
11 changes: 11 additions & 0 deletions src/logarithm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,17 @@ function Base.show(io::IO, x::Level)
nothing
end

function Base.alignment(io::IO, x::Gain)
length = printed_length(io, x)
left, _ = Base.alignment(io, x.val)
return left, length - left
end
function Base.alignment(io::IO, x::Level)
length = printed_length(io, x)
left, _ = Base.alignment(io, ustrip(x))
return left, length - left
end

BracketStyle(::Type{<:Union{Level,Gain}}) = SquareBrackets()

"""
Expand Down
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,12 @@ Base.show(io::IO, ::MIME"text/plain", ::Foo) = print(io, "42.0")
@test repr(1.0 * u"m * s * kg^(-1//2)") ==
(Sys.isapple() ? "1.0 m s kg⁻¹ᐟ²" : "1.0 m s kg^-1/2")
end
@test Base.alignment(stdout, (1//3)m) == Base.alignment(stdout, 1//3) .+ (0, 2)
@test Base.alignment(stdout, (2+3im)m) == Base.alignment(stdout, 2+3im) .+ (1, 3)
@test Base.alignment(stdout, 3.0dB) == Base.alignment(stdout, 3.0) .+ (0, 3)
@test Base.alignment(stdout, 3.0dBm) == Base.alignment(stdout, 3.0) .+ (0, 4)
@test Base.alignment(stdout, 3.0dB*s) == Base.alignment(stdout, 3.0) .+ (1, 6)
@test Base.alignment(stdout, 3.0dBm*s) == Base.alignment(stdout, 3.0) .+ (1, 7)
end

@testset "DimensionError message" begin
Expand Down

0 comments on commit eb46f21

Please sign in to comment.