Skip to main content

encode_packed_decimal

Function encode_packed_decimal 

Source
pub fn encode_packed_decimal(
    value: &str,
    digits: u16,
    scale: i16,
    signed: bool,
) -> Result<Vec<u8>>
Expand description

Encode packed decimal (COMP-3) field

Encodes decimal values to COMP-3 packed decimal format where each byte contains two decimal digits (nibbles), with the last nibble containing the sign. This function is optimized for high-throughput enterprise data processing.

§Arguments

  • value - String representation of the decimal value to encode
  • digits - Number of decimal digits in the field (1-18 supported)
  • scale - Number of decimal places (can be negative for scaling)
  • signed - Whether the field is signed (true) or unsigned (false)

§Returns

A vector of bytes containing the encoded packed decimal

§Errors

Returns an error if the value cannot be encoded as a packed decimal with the specified parameters.

§Performance

This function uses optimized digit extraction to avoid format!() allocation overhead.

§Examples

§Basic Positive Value

use copybook_codec::numeric::{encode_packed_decimal};

// Encode "123" as COMP-3: [0x12, 0x3C] (12 positive, 3C = positive sign)
let encoded = encode_packed_decimal("123", 3, 0, true)?;
assert_eq!(encoded, [0x12, 0x3C]);

§Negative Value

use copybook_codec::numeric::{encode_packed_decimal};

// Encode "-456" as COMP-3: [0x04, 0x56, 0xD] (456 negative)
let encoded = encode_packed_decimal("-456", 3, 0, true)?;
assert_eq!(encoded, [0x04, 0x56, 0xD]);

§Decimal Scale

use copybook_codec::numeric::{encode_packed_decimal};

// Encode "12.34" with 2 decimal places: [0x12, 0x34, 0xC]
let encoded = encode_packed_decimal("12.34", 4, 2, true)?;
assert_eq!(encoded, [0x12, 0x34, 0xC]);

§Unsigned Field

use copybook_codec::numeric::{encode_packed_decimal};

// Unsigned "789": [0x07, 0x89, 0xF] (F = unsigned sign)
let encoded = encode_packed_decimal("789", 3, 0, false)?;
assert_eq!(encoded, [0x07, 0x89, 0xF]);

§Zero Value

use copybook_codec::numeric::{encode_packed_decimal};

// Zero: [0x00, 0x0C]
let encoded = encode_packed_decimal("0", 2, 0, true)?;
assert_eq!(encoded, [0x00, 0x0C]);

§See Also