Skip to content

Added support for Arbitrary#163

Open
LucaCappelletti94 wants to merge 4 commits intoakubera:trunkfrom
LucaCappelletti94:arbitrary
Open

Added support for Arbitrary#163
LucaCappelletti94 wants to merge 4 commits intoakubera:trunkfrom
LucaCappelletti94:arbitrary

Conversation

@LucaCappelletti94
Copy link
Copy Markdown

@LucaCappelletti94 LucaCappelletti94 commented Feb 4, 2026

This PR adds support for the arbitrary crate by implementing the Arbitrary trait for BigDecimal. This enables using BigDecimal with fuzzing tools like cargo-fuzz and libfuzzer, and more importantly allows to use the Arbitrary derive in third party structs which include this struct as a field.

A new optional feature fuzz has been added to Cargo.toml:

[features]
fuzz = ["std", "arbitrary", "num-bigint/arbitrary"]

Note: The feature is named fuzz (not arbitrary) to avoid a name collision with the dependency, which is required for compatibility with older Cargo versions (pre-1.60). The feature requires std because the arbitrary crate itself does not support no_std

Implementation Details

To prevent memory allocation failures during fuzzing, the implementation limits the generated scale to ±1,000,000. Without this limit, extremely large scale values could cause the BigDecimal to attempt allocating massive amounts of memory when converted to strings or performing certain operations.

  • New module: src/impl_arbitrary.rs implementing Arbitrary<'a> for BigDecimal
  • Implements all three trait methods:
    • arbitrary() - Generate a random BigDecimal from unstructured data
    • arbitrary_take_rest() - Consume all remaining data to generate a BigDecimal
    • size_hint() - Provide size hints for the fuzzer

Usage

Enable the feature in your Cargo.toml:

[dependencies]
bigdecimal = { version = "0.4", features = ["fuzz"] }

Example fuzz target:

#![no_main]
use libfuzzer_sys::fuzz_target;
use bigdecimal::BigDecimal;

fuzz_target!(|data: BigDecimal| {
    // Your fuzzing logic here
    let _ = data.to_string();
    let _ = data.sqrt();
});

Closes #122

@LucaCappelletti94
Copy link
Copy Markdown
Author

For added context, this PR is needed to allow for adding Arbitrary derives in sqlparser, as shown here: apache/datafusion-sqlparser-rs#2193

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

impl Arbitrary for BigDecimal

1 participant