Skip to content

Decimal with zero length bytes can be constructed and decoded but fails to encode #680

Closed

Description

@hvnsweeting
    #[test]
    fn test_round_trip_decimal_length_zero() -> TestResult {
        use crate::decode::decode;
        use crate::encode::encode;
        use crate::encode::tests::success;

        let schema = Schema::parse_str(
            r#"{"type": "bytes", "logicalType": "decimal", "precision": 4, "scale": 2}"#,
        )?;
        let expected = Value::Decimal(Decimal::from(Vec::<u8>::new()));
        dbg!(&expected);
        // 0x00 is the varint encoding of length 0 (zero-length bytes)
        let mut buf: &[u8] = &[0x00];
        let decoded = decode(&schema, &mut buf)?;
        assert_eq!(decoded, expected);

        // Re-encoding the decoded value should round-trip, but it fails
        let mut buffer = Vec::new();
        encode(&decoded, &schema, &mut buffer).expect(&success(&decoded, &schema));

        Ok(())
    }

Output:

---- types::tests::test_round_trip_decimal_length_zero stdout ----
[avro/src/types.rs:1921:9] &expected = Decimal(
    Decimal {
        value: 0,
        len: 0,
    },
)

thread 'types::tests::test_round_trip_decimal_length_zero' (126727) panicked at avro/src/types.rs:1929:48:
Value: Decimal(Decimal { value: 0, len: 0 })
 should encode with schema:
Decimal(DecimalSchema { precision: 4, scale: 2, inner: Bytes }): Error { details: Number of bytes requested for decimal sign extension 0 is less than the number of bytes needed to decode 1 }


failures:
    types::tests::test_round_trip_decimal_length_zero

For avro cpp, it treats this as bytes so it succeeds in both encode/decode.
Java failed to decode.

Exception in thread "main" java.lang.NumberFormatException: Zero length BigInteger
        at java.base/java.math.BigInteger.<init>(BigInteger.java:312)
        at java.base/java.math.BigInteger.<init>(BigInteger.java:346)
        at org.apache.avro.Conversions$DecimalConversion.fromBytes(Conversions.java:111)
        at DecimalTest.main(DecimalTest.java:19)

I'm happy to make PR to fix this but it first needs to decide which behavior whether to:

  • reject on decode (like java)
  • accept and fix encode so it can round-trip (like cpp)

Activity

  1. Kriskras99 commented on Sep 16, 2026

    @Kriskras99
    Contributor

    Thanks for the bug report! Doing it the C++ way would mean special casing BigInt::ZERO with length == 0 so I decided to reject it like Java.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions