From f480cc50bd7c42ef1ae78bc7ed0746c4314d39aa Mon Sep 17 00:00:00 2001 From: Jan Wagner Date: Sat, 15 Mar 2025 17:12:48 +0100 Subject: [PATCH] fix Base.GMP.MPZ.export! on uninitialized vectors fixing Base.GMP.MPZ.export! not initializing memory when resizing vector fixing Base.GMP.MPZ.export! not initializing memory, nonzero vectors are only partially overwritten by :__gmpz_export, leading to unexpected results fixing Base.GMP.MPZ.export! not initializing memory when `n` is zero. if `n` is zero :__gmpz_export does not touch target vector adding test cases for fixed issues --- base/gmp.jl | 1 + test/gmp.jl | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/base/gmp.jl b/base/gmp.jl index 97488551f60f6..033cf3fe75fde 100644 --- a/base/gmp.jl +++ b/base/gmp.jl @@ -257,6 +257,7 @@ function export!(a::AbstractVector{T}, n::BigInt; order::Integer=-1, nails::Inte stride(a, 1) == 1 || throw(ArgumentError("a must have stride 1")) ndigits = cld(sizeinbase(n, 2), 8*sizeof(T) - nails) length(a) < ndigits && resize!(a, ndigits) + fill!(a, zero(T)) count = Ref{Csize_t}() ccall((:__gmpz_export, libgmp), Ptr{T}, (Ptr{T}, Ref{Csize_t}, Cint, Csize_t, Cint, Csize_t, mpz_t), a, count, order, sizeof(T), endian, nails, n) diff --git a/test/gmp.jl b/test/gmp.jl index 0812775672969..45fec17f82d1d 100644 --- a/test/gmp.jl +++ b/test/gmp.jl @@ -481,6 +481,18 @@ end bytes_to_export_to = Vector{UInt8}(undef, 2) Base.GMP.MPZ.export!(bytes_to_export_to, int_to_export_from, order=0) @test all(bytes_to_export_to .== bytes_to_import_from) + + # test export of 0 is T[0] + zero_to_export = BigInt(0) + bytes_to_export_to = Vector{UInt8}(undef, 0) + Base.GMP.MPZ.export!(bytes_to_export_to, zero_to_export, order=0) + @test bytes_to_export_to == UInt8[0] + + # test export on nonzero vector + x_to_export = BigInt(6) + bytes_to_export_to = Vector{UInt8}([1, 2, 3, 4, 5]) + Base.GMP.MPZ.export!(bytes_to_export_to, x_to_export, order=0) + @test bytes_to_export_to == UInt8[6, 0, 0, 0, 0] end @test isqrt(big(4)) == 2