Functional Weave
Code in Rust

validation.gtin

Check an EAN-8, UPC-A, EAN-13 or GTIN-14 barcode number against the GS1 mod-10 check digit.

1.1.0 · published 2026-10-03 by charlie · Anterra

Pinned by 19 tests, run in TypeScript, Python and Rust.

What it does

Checks a Global Trade Item Number - the number under a retail barcode - in any of its four lengths: EAN-8 (8 digits), UPC-A (12), EAN-13 (13) and GTIN-14 (14, used on cases and pallets). All four share one GS1 check digit: weight the digits 3, 1, 3, 1 ... starting from the digit just left of the check digit and moving left, sum, and the check digit is whatever brings the sum up to a multiple of ten.

Since 1.1.0 the check digit arithmetic comes from `validation.gs1-check-digit`, which serves every GS1 key length; the answers are the same as 1.0.0's. Use that capability directly to compute a check digit or to check a key that is not a GTIN.

For example

  • validate_gtin(4006381333931) → valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason — an EAN-13, the standard retail barcode
  • validate_gtin(036000291452) → valid true, normalised 036000291452, kind upc-a, gtin14 00036000291452, reason — a UPC-A: its first digit is weighted 3, not 1
  • validate_gtin(96385074) → valid true, normalised 96385074, kind ean-8, gtin14 00000096385074, reason — an EAN-8, the other length a left-weighted check gets wrong

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn validate_gtin(value: &str) -> GtinCheck
valuestring8, 12, 13 or 14 digits, optionally grouped with spaces or hyphens
returnsGtinCheck

The type it declares, generated into your project

/// The result of checking a GTIN. Every string is null when valid is false; reason is null when it is true.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GtinCheck {
    pub valid: bool,
    /// the digits only, at the length given
    pub normalised: Option<String>,
    /// ean-8, upc-a, ean-13 or gtin-14, from the length
    pub kind: Option<String>,
    /// left-padded with zeros to 14 digits, the form to compare and store
    pub gtin14: Option<String>,
    /// empty, bad-character, bad-length, all-zero or bad-check-digit
    pub reason: Option<String>,
}

Your code names it in one line, in the file that uses it

fune!(validation.gtin@^1);  // then call validate_gtin(…)
impl/rust.rs · 75 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::validation_gs1_check_digit::is_gs1_check_digit_valid;  ← from validation.gs1-check-digit ^1.0.0 · built alongside by fune

fn invalid(reason: &str) -> GtinCheck {
    GtinCheck {
        valid: false,
        normalised: None,
        kind: None,
        gtin14: None,
        reason: Some(reason.to_string()),
    }
}

/// Check an EAN-8, UPC-A, EAN-13 or GTIN-14 against the GS1 mod-10 check digit.
///
/// A pass means the number was typed correctly, not that GS1 issued it.
/// Validators answer rather than panic: a malformed value is the answer "no".
pub fn validate_gtin(value: &str) -> GtinCheck {
    // Barcodes are printed in groups, so spaces and hyphens are ignored anywhere.
    let chars: Vec<char> = value.chars().filter(|ch| *ch != ' ' && *ch != '-').collect();
    if chars.is_empty() {
        return invalid("empty");
    }
    if chars.iter().any(|ch| !ch.is_ascii_digit()) {
        return invalid("bad-character");
    }
    let kind = match chars.len() {
        8 => "ean-8",
        12 => "upc-a",
        13 => "ean-13",
        14 => "gtin-14",
        _ => return invalid("bad-length"),
    };
    // Zero everywhere satisfies the arithmetic and has never been allocated.
    if chars.iter().all(|ch| *ch == '0') {
        return invalid("all-zero");
    }

    // The GS1 mod-10 check, weighted from the right, which is what makes one
    // rule serve all four lengths (EAN-13's first digit gets 1, EAN-8's and
    // UPC-A's get 3).
    let digits: String = chars.iter().collect();
    if !is_gs1_check_digit_valid(&digits) {
        return invalid("bad-check-digit");
    }

    GtinCheck {
        valid: true,
        gtin14: Some(format!("{:0>14}", digits)),
        normalised: Some(digits),
        kind: Some(kind.to_string()),
        reason: None,
    }
}

/// Object keys are camelCase to match the shared vectors.
pub fn gtin_check_to_value(result: &GtinCheck) -> Value {
    let text = |field: &Option<String>| match field {
        Some(s) => Value::str(s),
        None => Value::Null,
    };
    Value::obj(vec![
        ("valid", Value::Bool(result.valid)),
        ("normalised", text(&result.normalised)),
        ("kind", text(&result.kind)),
        ("gtin14", text(&result.gtin14)),
        ("reason", text(&result.reason)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    // A non-string argument arrives here as an empty string, which is exactly
    // the answer TypeScript and Python give for a non-string: empty.
    gtin_check_to_value(&validate_gtin(args[0].as_str()))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add validation.gtin
Download for Rust validation.gtin-1.1.0-rust.fune · 11,928 bytes sha256 5cf7c1608fdd61589de54c71b1957dd39a67df201c8f06ec7f1b417035565641

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./validation.gtin-1.1.0-rust.fune, or fetch it from a terminal with fune pull validation.gtin@1.1.0:rust.

The whole function, every language, is one file too: validation.gtin-1.1.0.fune, 15,693 bytes, sha256 34abcea03c11dbc84715b68a15149e3b346a65ea45084ac80d49792f3adec583. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before validation.gtin

after — your function gets the result and the arguments, and returns the final result.

// fune: after validation.gtin

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace validation.gs1-check-digit in validation.gtin

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show validation.gtin --steps.

// fune: step validation.gtin after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
an EAN-13, the standard retail barcode 4006381333931 → valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason —
a UPC-A: its first digit is weighted 3, not 1 036000291452 → valid true, normalised 036000291452, kind upc-a, gtin14 00036000291452, reason —
an EAN-8, the other length a left-weighted check gets wrong 96385074 → valid true, normalised 96385074, kind ean-8, gtin14 00000096385074, reason —
a GTIN-14 case code built from the UPC-A with indicator 1 10036000291459 → valid true, normalised 10036000291459, kind gtin-14, gtin14 10036000291459, reason —
the UPC-A padded to GTIN-14 is the same number 00036000291452 → valid true, normalised 00036000291452, kind gtin-14, gtin14 00036000291452, reason —
a Bookland EAN-13, which is an ISBN 9780306406157 → valid true, normalised 9780306406157, kind ean-13, gtin14 09780306406157, reason —
printed groups with spaces and hyphens 4 006381-333931 → valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason —
last digit off by one 4006381333932 → valid false, normalised —, kind —, gtin14 —, reason bad-check-digit
two adjacent digits transposed: a plain digit sum would miss it 4006383133931 → valid false, normalised —, kind —, gtin14 —, reason bad-check-digit
eleven digits is no GTIN length 03600029145 → valid false, normalised —, kind —, gtin14 —, reason bad-length
Show the other 9 tests
CaseArgumentsExpected
fifteen digits is too long 100360002914590 → valid false, normalised —, kind —, gtin14 —, reason bad-length
a letter is a bad character, reported before the length 40063813339A → valid false, normalised —, kind —, gtin14 —, reason bad-character
a dot is not an accepted separator 4006381.333931 → valid false, normalised —, kind —, gtin14 —, reason bad-character
all zeros satisfies the arithmetic but is refused 00000000 → valid false, normalised —, kind —, gtin14 —, reason all-zero
the empty string → valid false, normalised —, kind —, gtin14 —, reason empty
separators only is empty - → valid false, normalised —, kind —, gtin14 —, reason empty
a non-string is empty, not an exception — → valid false, normalised —, kind —, gtin14 —, reason empty
GS1's check digit worked example, GTIN-13 6291041500213 6291041500213 → valid true, normalised 6291041500213, kind ean-13, gtin14 06291041500213, reason —
an 18-digit SSCC has a good check digit but is no GTIN length 376104250021234569 → valid false, normalised —, kind —, gtin14 —, reason bad-length

More from the author

Weighting from the right is the detail home-grown validators get wrong. EAN-13 weights its first digit 1, but EAN-8 and UPC-A weight their first digit 3, so code that always starts at the left with 1 accepts only EAN-13 and GTIN-14.

A PASSING NUMBER IS WELL FORMED, NOT ALLOCATED. The check catches every single mistyped digit and most adjacent transpositions. It cannot say whether GS1 has issued the number or what product it is on; only GS1's registry (Verified by GS1) can.

RESULT: `valid`, then on success the digits (`normalised`), the `kind` implied by the length, and `gtin14`, the number left-padded with zeros to 14 digits. GS1 defines every GTIN as a 14-digit number with leading zeros, so `gtin14` is the form to store and compare: the UPC-A 036000291452 and the EAN-13 0036000291452 are the same item. `kind` is read from the length as given; an EAN-13 beginning with 0 is not re-labelled as a UPC-A.

ACCEPTED INPUT: ASCII digits, with ASCII spaces and hyphens ignored anywhere, because barcodes are printed in groups ("5 012345 678900"). Anything else makes the value invalid.

| reason | meaning | |-------------------|----------------------------------------------------------| | `empty` | nothing but spaces and hyphens, or not a string at all | | `bad-character` | something other than a digit, space or hyphen | | `bad-length` | not 8, 12, 13 or 14 digits | | `all-zero` | every digit is 0: satisfies the arithmetic, never issued | | `bad-check-digit` | the last digit does not match |

The checks run in that order and the first failure is the reason. Validators answer rather than throw.

Out of scope: GS1 prefix meaning (country of the member organisation, 978/979 Bookland, 02/20-29 restricted in-store numbers), GTIN-12 zero-suppressed UPC-E, and add-on codes. For ISBNs use validation.isbn, which also checks the prefix.

Source: GS1 General Specifications, section 7.9 "Check digit calculation" (https://www.gs1.org/services/how-calculate-check-digit-manually).

Files

PathBytes
README.md2,815
impl/python.py1,833
impl/rust.rs2,514
impl/typescript.ts1,730
vectors.json3,729