Avatar of nathanjent

nathanjent's solution

to Luhn From in the Rust Track

Published at Jul 22 2019 · 0 comments
Instructions
Test suite
Solution

Luhn: Using the From Trait

Before doing this exercise you should probably do the original Luhn exercise. If you have not completed Luhn, you can get it by running the command:

exercism download --exercise=luhn --track=rust

In the original Luhn exercise you only validated strings, but the Luhn algorithm can be applied to integers as well.

In this exercise you'll implement the From trait to convert strings, strs and unsigned integers into a Struct that performs the validation.

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

Submitting the solution

Generally you should submit all files in which you implemented your solution (src/lib.rs in most cases). If you are using any external crates, please consider submitting the Cargo.toml file. This will make the review process faster and clearer.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Source

The Rust track maintainers, based on the original Luhn exercise

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

luhn-from.rs

use luhn_from::*;

#[test]
fn you_can_validate_from_a_str() {
    let valid = Luhn::from("046 454 286");
    let invalid = Luhn::from("046 454 287");
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_string() {
    let valid = Luhn::from(String::from("046 454 286"));
    let invalid = Luhn::from(String::from("046 454 287"));
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_u8() {
    let valid = Luhn::from(240u8);
    let invalid = Luhn::from(241u8);
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_u16() {
    let valid = Luhn::from(64_436u16);
    let invalid = Luhn::from(64_437u16);
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_u32() {
    let valid = Luhn::from(46_454_286u32);
    let invalid = Luhn::from(46_454_287u32);
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_u64() {
    let valid = Luhn::from(8273_1232_7352_0562u64);
    let invalid = Luhn::from(8273_1232_7352_0569u64);
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn you_can_validate_from_a_usize() {
    let valid = Luhn::from(8273_1232_7352_0562usize);
    let invalid = Luhn::from(8273_1232_7352_0569usize);
    assert!(valid.is_valid());
    assert!(!invalid.is_valid());
}

#[test]
#[ignore]
fn single_digit_string_is_invalid() {
    assert!(!Luhn::from("1").is_valid());
}

#[test]
#[ignore]
fn single_zero_string_is_invalid() {
    assert!(!Luhn::from("0").is_valid());
}

#[test]
#[ignore]
fn valid_canadian_sin_is_valid() {
    assert!(Luhn::from("046 454 286").is_valid());
}

#[test]
#[ignore]
fn invalid_canadian_sin_is_invalid() {
    assert!(!Luhn::from("046 454 287").is_valid());
}

#[test]
#[ignore]
fn invalid_credit_card_is_invalid() {
    assert!(!Luhn::from("8273 1232 7352 0569").is_valid());
}

#[test]
#[ignore]
fn strings_that_contain_non_digits_are_invalid() {
    assert!(!Luhn::from("046a 454 286").is_valid());
}
pub struct Luhn(String);

impl Luhn {
    pub fn is_valid(&self) -> bool {
        //unimplemented!("Determine if the current Luhn struct contains a valid credit card number.");

        let no_spaces = self.0.replace(" ", "");
        match no_spaces.parse::<usize>() {
            Ok(_) => {
                let total: u8 = no_spaces
                    .rsplit("")
                    .filter_map(|s| str::parse::<u8>(s).ok())
                    .enumerate()
                    .map(|(i, n)| {
                        if i % 2 == 0 {
                            n
                        } else {
                            let double = n * 2;
                            if double > 9 {
                                double - 9
                            } else {
                                double
                            }
                        }
                    })
                    .sum();
                if total < 1 {
                    return false;
                }
                total % 10 == 0
            }
            Err(_) => false,
        }
    }
}

impl<T> From<T> for Luhn
where
    T: ToString,
{
    fn from(input: T) -> Self {
        Luhn(input.to_string())
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

nathanjent's Reflection

I'm sure performance could be improved but It works.