Skip to content

Commit

Permalink
Merge pull request #18855 from H-225/h5/fix18849
Browse files Browse the repository at this point in the history
Add overloads for `bin`, `oct`, `dec` and `hex` to avoid calling `sizeof` on `BigInt`s
  • Loading branch information
kshyatt authored Oct 10, 2016
2 parents e94007e + c747309 commit b8f98a0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,19 @@ oct(n::BigInt) = base( 8, n)
dec(n::BigInt) = base(10, n)
hex(n::BigInt) = base(16, n)

for f in (:bin, :oct, :dec, :hex)
@eval function ($f)(n::BigInt, pad::Int)
b = IOBuffer()
res = ($f)(n)
diff = pad - length(res)
for _ in 1:diff
write(b, "0")
end
write(b, res)
String(b)
end
end

function base(b::Integer, n::BigInt)
2 <= b <= 62 || throw(ArgumentError("base must be 2 ≤ base ≤ 62, got $b"))
p = ccall((:__gmpz_get_str,:libgmp), Ptr{UInt8}, (Ptr{UInt8}, Cint, Ptr{BigInt}), C_NULL, b, &n)
Expand Down
14 changes: 14 additions & 0 deletions test/bigint.jl
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,20 @@ end
@test oct(-big(9)) == "-11"
@test hex(big(12)) == "c"

# Issue #18849: bin, oct, dec, hex should not call sizeof on BigInts
# when padding is desired
let padding = 4, low = big(4), high = big(2^20)
@test bin(low, padding) == "0100"
@test oct(low, padding) == "0004"
@test dec(low, padding) == "0004"
@test hex(low, padding) == "0004"

@test bin(high, padding) == "100000000000000000000"
@test oct(high, padding) == "4000000"
@test dec(high, padding) == "1048576"
@test hex(high, padding) == "100000"
end

@test isqrt(big(4)) == 2
@test isqrt(big(5)) == 2

Expand Down

0 comments on commit b8f98a0

Please sign in to comment.