Sha256: 264a09f436e949e79f806625ab4df62f7be65efe78c275a71a4c4bffabb6361a

Contents?: true

Size: 1.29 KB

Versions: 118

Compression:

Stored size: 1.29 KB

Contents

/// An ISBN type
#[derive(PartialEq, Eq)]
enum IsbnType {
    Isbn10,
    Isbn13,
}

/// Checks if an 'X' is valid at the given position for the given ISBN type
#[allow(non_snake_case)]
fn is_X_valid(position: &usize, isbn_type: &IsbnType) -> bool {
    (isbn_type == &IsbnType::Isbn10 && position == &9 ) ||
    (isbn_type == &IsbnType::Isbn13 && position == &12)
}

/// Checks if a '-' is valid at the given position for the given ISBN type
fn is_dash_valid(position: &usize, isbn_type: &IsbnType) -> bool {
    isbn_type == &IsbnType::Isbn13 &&
    (position == &1 || position == &5 || position == &11)
}

/// Determines whether the supplied string is a valid ISBN number
pub fn is_valid_isbn(isbn: &str) -> bool {
    let isbn_type = match isbn.len() {
        10 => IsbnType::Isbn10,
        13 => IsbnType::Isbn13,
        _ => return false,
    };

    let mut checksum = 0;
    let mut coefficient = 10;
    for (position, c) in isbn.char_indices() {
        let digit_value = match c {
            '0' ... '9' => c.to_digit(10).unwrap(),
            'X' if is_X_valid(&position, &isbn_type) => 10,
            '-' if is_dash_valid(&position, &isbn_type) => continue,
            _   => return false,
        };

        checksum += coefficient * digit_value;
        coefficient -= 1;
    }

    checksum % 11 == 0
}

Version data entries

118 entries across 118 versions & 1 rubygems

Version Path
trackler-2.2.1.179 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.178 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.177 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.176 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.175 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.174 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.173 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.172 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.171 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.170 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.169 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.167 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.166 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.165 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.164 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.163 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.162 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.161 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.160 tracks/rust/exercises/isbn-verifier/example.rs
trackler-2.2.1.159 tracks/rust/exercises/isbn-verifier/example.rs