diff --git a/src/methods.jl b/src/methods.jl index 6935557..66e7446 100644 --- a/src/methods.jl +++ b/src/methods.jl @@ -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 diff --git a/test/ndigits.jl b/test/ndigits.jl new file mode 100644 index 0000000..33fc1bb --- /dev/null +++ b/test/ndigits.jl @@ -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 \ No newline at end of file diff --git a/test/runtests.jl b/test/runtests.jl index edeffaa..1651109 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -19,6 +19,7 @@ include("comparisons.jl") include("sums.jl") include("broadcasting.jl") include("bitintegers.jl") +include("ndigits.jl") # ============================================================================ # Static analysis