Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/methods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ Base.:/(x::T, y::T) where T<:EmulatedInteger = x[] / y[] # Should result in Floa
Base.show(io::IO, x::T) where T<:EmulatedUnsigned = print(io, "0x", string(x[], pad=hexdigits(T), base=16))
Base.show(io::IO, x::EmulatedSigned) = show(io, x[])

Base.ndigits(x::EmulatedInteger; base::Integer=10, pad::Integer=1) = ndigits(x[]; base, pad)

# Per Julia convention, `sign` returns a value of the same type as its argument. The storage-level `sign` produces 0/1/-1, all of which round-trip through `% T` cleanly. The edge case `Int1` (range `{-1, 0}`) is fine too: a 1-bit signed type can never hold a positive value, so `sign(x[])` is always `0` or `-1` — never `+1` — and no modular wrap-around happens.
Base.sign(x::T) where T<:EmulatedInteger = sign(x[]) % T
Base.signbit(x::EmulatedInteger) = x[] |> signbit
Expand Down
20 changes: 20 additions & 0 deletions test/ndigits.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
@testset "ndigits" begin
@emulate Int3 UInt3 Int3_128 Int129 UInt129

@test ndigits(typemin(Int129); base=2) == 129
@test ndigits(typemin(Int129)) == 39
@test ndigits(typemin(Int3); base=2) == 3

for Source in (Int3, UInt3, Int3_128, Int129, UInt129)
for x in (typemin(Source), typemin(Source) + one(Source), zero(Source), typemax(Source))
expected = BigInt(x[])
@test (@inferred ndigits(x)) == ndigits(expected)
for base in (-16, -2, 2, 3, 10, 16), pad in (0, 1, 150)
@test (@inferred ndigits(x; base, pad)) == ndigits(expected; base, pad)
end
end
for base in (-1, 0, 1)
@test_throws DomainError ndigits(zero(Source); base)
end
end
end
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ include("comparisons.jl")
include("sums.jl")
include("broadcasting.jl")
include("bitintegers.jl")
include("ndigits.jl")

# ============================================================================
# Static analysis
Expand Down