#luhn #checksum

no-std luhn3

A Luhn validation library

5 stable releases

1.1.0 Oct 30, 2021
1.0.4 Oct 24, 2021

#1564 in Algorithms

Download history 740/week @ 2024-06-16 527/week @ 2024-06-23 664/week @ 2024-06-30 757/week @ 2024-07-07 510/week @ 2024-07-14 809/week @ 2024-07-21 588/week @ 2024-07-28 387/week @ 2024-08-04 382/week @ 2024-08-11 315/week @ 2024-08-18 442/week @ 2024-08-25 414/week @ 2024-09-01 242/week @ 2024-09-08 326/week @ 2024-09-15 408/week @ 2024-09-22 313/week @ 2024-09-29

1,291 downloads per month

MIT license

20KB
225 lines

Validates strings and computes check digits using the Luhn algorithm.

This is a fast, allocation and panic free crate for computing and validating Luhn checksum for decimal and alpha numeric sequences. This is my crate. There are many like it, but this one is mine.

It's not a great checksum, but it's used in a bunch of places:

  • credit card numbers
  • International Securities Identification Number (ISIN) codes
  • International Mobile Equipment Identity (IMEI) codes
  • Canadian Social Insurance Numbers

More information is available on wikipedia.

Usage

Add luhn3 under [dependencies] in your Cargo.toml:

[dependencies]
luhn3 = "1.1"

Most of the CC numbers use Luhn checksum:

// Visa
luhn3::valid(b"4111111111111111"); // true

// MasterCard
luhn3::valid(b"5555555555554444"); // true

// Invalid Visa
luhn3::valid(b"4111111111111121"); // false

Library also allows to calculate a checksum if missing:

// Take off the checksum from American Express card number
let (&check, body) = b"378282246310005".split_last().unwrap();
// and recalculate it
luhn3::checksum(body); // Some(b'5')

This library provides two sets of operation: decimal and alphanum.

  • decimal operates on sequences composed of decimal numbers only, such as credit card numbers or IMEI codes
  • alphanum operates on sequences composed of decimal numbers and capital latin letters, such as ISIN or NSIN

no_std

Crate doesn't use std

Performance

Library contains scalar implementations for both decimal and alhpanumeric inputs. For validations there are variants that take a slice and variants that take an array. The only difference is that compiler can optimize operations on array better so they are slightly faster.

validate isin           time:   [13.136 ns 13.181 ns 13.230 ns]
validate isin arr       time:   [9.5167 ns 9.5647 ns 9.6168 ns]
validate visa           time:   [8.3910 ns 8.4963 ns 8.6302 ns]
validate visa arr       time:   [5.3921 ns 5.4192 ns 5.4487 ns]

For non 64bit platforms implementation operating on alphanumeric input might perform better.

No runtime deps