#u64 #optional #serial #numbers #serde #parser #field

tktax-serde

Serde utilities for parsing check or serial number fields with optional u64 values

1 unstable release

new 0.2.2 Feb 1, 2025

#70 in #u64


Used in 14 crates (via tktax-transaction)

Apache-2.0

43KB
194 lines

Overview

This crate provides custom Serde utilities focused on parsing check or serial numbers into an optional u64. An empty string is interpreted as None, while numeric strings and integral values are parsed as Some(u64).

Features

  • Optional Parsing: Attempts to parse an incoming field as a u64, returning None if the field is empty.
  • Robust Error Handling: Produces structured Serde errors for malformed input, ensuring safe deserialization in production.

Usage

Add the following to your Cargo.toml:

[dependencies]
tktax-serde = "0.1.0"
serde = "1.0"
serde_json = "1.0"

Import and apply the custom deserializer:

use serde::Deserialize;
use tktax_serde::parse_check_or_serial_number_opt;

#[derive(Debug, Deserialize)]
struct MyStruct {
    // This field will be deserialized via our custom parser
    #[serde(deserialize_with = "parse_check_or_serial_number_opt")]
    check_number: Option<u64>,
}

Example

fn main() -> Result<(), serde_json::Error> {
    let json_data_empty = r#"{"check_number": ""}"#;
    let parsed_empty: MyStruct = serde_json::from_str(json_data_empty)?;
    assert_eq!(parsed_empty.check_number, None);

    let json_data_numeric = r#"{"check_number": "42"}"#;
    let parsed_numeric: MyStruct = serde_json::from_str(json_data_numeric)?;
    assert_eq!(parsed_numeric.check_number, Some(42));

    let json_data_int = r#"{"check_number": 123}"#;
    let parsed_int: MyStruct = serde_json::from_str(json_data_int)?;
    assert_eq!(parsed_int.check_number, Some(123));

    Ok(())
}

Testing

Run tests using:

cargo test --package tktax-serde

The comprehensive test suite verifies empty string handling, numeric string conversion, and numeric literal conversion, ensuring proper adherence to expected deserialization behavior.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Open a pull request

Issues and pull requests are welcomed to improve functionality, fix bugs, or enhance documentation.


© 2025 tktax-serde contributors. Licensed under the Apache-2.0 License.

Dependencies

~26–37MB
~641K SLoC