🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of mkantor

mkantor's solution

to Luhn From in the Rust Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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 fetch rust luhn

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 wich 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 specfic 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.

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

extern crate luhn_from;

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());
}
use LuhnData::*;

enum LuhnData {
    BadInput,
    GoodInput { number: u64 },
}

/// Iterate over digits in GoodInput's number, going from least to most significant digit.
/// Sadly enum variants aren't types, otherwise I could just impl Iterator for GoodInput.
impl Iterator for LuhnData {
    type Item = u64;
    fn next(&mut self) -> Option<Self::Item> {
        match *self {
            BadInput => None,
            GoodInput { number } if number == 0 => None,
            GoodInput { ref mut number } => {
                let digit = *number % 10;
                *number /= 10;
                Some(digit)
            }
        }
    }
}

pub struct Luhn {
    data: LuhnData,
}

impl Luhn {
    pub fn is_valid(self) -> bool {
        match self.data {
            BadInput => false,
            GoodInput { number } if number < 10 => false,
            data @ GoodInput { .. } => {
                data.enumerate()
                    .map(|(i, digit)| match i % 2 {
                             0 => digit,
                             _ => {
                                 match digit * 2 {
                                     output @ 0...9 => output,
                                     output => output - 9,
                                 }
                             }
                         })
                    .sum::<u64>() % 10 == 0
            }
        }
    }
}

impl<'a> From<&'a str> for Luhn {
    fn from(input: &'a str) -> Self {
        let mut number = 0;
        for (i, character) in input.chars().filter(|&c| c != ' ').enumerate() {
            match character.to_digit(10) {
                Some(digit) => {
                    // These casts are lame. Why doesn't Rust have things like this in std?
                    // impl Mul<u32> for u64 {
                    //     type Output = u64;
                    //     fn mul(self, rhs: u32) -> Self::Output {
                    //         self * rhs as u64
                    //     }
                    // }
                    // Also, I'm not sure why pow isn't part of Mul or in its own trait so it
                    // could be overloaded.
                    let multiplier = 10u64.pow(i as u32);
                    number += multiplier * digit as u64;
                }
                None => return Luhn { data: BadInput },
            }
        }
        Luhn { data: GoodInput { number: number } }
    }
}

impl From<String> for Luhn {
    fn from(input: String) -> Self {
        Luhn::from(input.as_str())
    }
}

macro_rules! from_uint_impl {
    ($t: ty) => {
        impl From<$t> for Luhn {
            fn from(input: $t) -> Self {
                Luhn { data: GoodInput { number: input as u64 } }
            }
        }
    }
}
from_uint_impl! { u8 }
from_uint_impl! { u16 }
from_uint_impl! { u32 }
from_uint_impl! { u64 }
from_uint_impl! { usize }

Community comments

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

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?